πŸ“ Problem Details

input array cost where cost[i] is the cost of the ith step can either climb one or two steps each turn can start from step 0 or step 1 return the min cost to reach the top floor

πŸ’­What Were My Initial Thoughts?

1. Can it be broken into subproblems?
	- yes
	- like climbing stairs, to reach step i, we can from from either i-1 or i-2
	- the cost of each step must be accounted for
	- the introduction of cost makes this similar to a Knapsack Problem

2. Choose Top-Down vs. Bottom-Up
	- bottom up is best in this case
	- avoids recursion overhead
	- allows for space optimization

3. Define DP State
	- dp[i] would represent the min cost to reach step[i]
	- since we can start from step 0 or step 1
		- init dp[0] = cost[0], dp[1] = cost[1]

4. Transition Formula
	- dp[i] = min(dp[iβˆ’1], dp[iβˆ’2]) + cost[i]
	- take the min cost path from i-1 or i-2 and add the current step's cost
	- final state is to reach the top 
		- min(dp[nβˆ’1],dp[nβˆ’2])
		- because the last step is not counted in cost

5. Optimize for Space
	- like climbing stairs, we only need the last two computations
	- reduces space complexity from O(n) to O(1)

πŸ’‘ Explanation of Solution

same as initial thoughts

βŒ› Complexity Analysis

Time Complexity: O(n)
Space Complexity: O(1)

πŸ’» Implementation of Solution

class Solution {
public:
    int minCostClimbingStairs(vector<int>& cost) {
        int n = cost.size();
 
        // base cases:
        int prev2 = cost[0];
        int prev1 = cost[1];
    
        for(int i=2; i < n; i++) {
            int curr = min(prev1,prev2) + cost[i];
            prev2 = prev1;
            prev1 = curr;
        }
 
        return min(prev1, prev2); // min cost to reach the top
    }
};