I need to confirm if my approach to finding the time and space complexity for the below algorithm is correct:
I have an input list and we can take the following as an example : [1,100,1,1,1,100,1,1,100,1] and let us call the given list as cost. I am modifying the given list as per my algorithm below
My algorithm:
- Loop through the list (starting from position 2) till the end of the input list.
- We perform the following operation: cost[i] = cost[i] + min(cost[i-1],cost[i-2])
- We eventually check for the last 2 elements and take the minimum value from the last two elements = min = min(last element,second last element).
My approach to calculate the time complexity : 1. For step 1 = O(n) 2. For step 2 = O(1) + O(n) (to calculate the minimum among the two elements) 3. For step 3 = O(1)
Hence Time complexity = O(n) + O(1) + O(n) + O(1) = O(n) . Space complexity = O(n) [ Simple assumption that the space required will be to store the list]. Can someone please let me know if my approach to calculate the complexities is valid?
Regards, Anubhav