You are given an integer array
cost
wherecost[i]
is the cost ofith
step on a staircase. Once you pay the cost, you can either climb one or two steps.You can either start from the step with index
0
, or the step with index1
.Return the minimum cost to reach the top of the floor.
Classical dp question.
you can either climb one or two steps. We can simply set the dp[i] to be the minimum cost to reach index i and we will return dp[cost.size()]. It is a pretty intuitive solution.
class Solution {
public:
int minCostClimbingStairs(vector<int>& cost) {
int a = 0, b = 0, c = 0;
for(int i = 2; i <= cost.size(); i++){
c = min(a + cost[i - 2], b + cost[i - 1]);
a = b;
b = c;
}
return c;
}
};
Can we optimize the space complexity?
Yes, actually it can be reduced to O(1). How?
As we can see the dp[i] only relies on dp[i - 1] and dp[i - 2], we can simply use two variable to replace the whole dp array.
you can see the a, b, c represent dp[i - 2], dp[i - 1] and dp[i] respectively. We just need to swap the value of a, b, c and achieve the same output as using dp array.
class Solution {
public:
int minCostClimbingStairs(vector<int>& cost) {
int a = 0, b = 0, c = 0;
for(int i = 2; i <= cost.size(); i++){
c = min(a + cost[i - 2], b + cost[i - 1]);
a = b;
b = c;
}
return c;
}
};