746. Min Cost Climbing Stairs
Problem
cost[i] is what you pay when you leave step i, after which you climb 1 or 2 steps. You may start on step 0 or step 1. Return the minimum cost to get past the last step.
Example: [10,15,20] → 15; [1,100,1,1,1,100,1,1,100,1] → 6
dp[i] = min cost to stand on step i = min(dp[i−1] + cost[i−1], dp[i−2] + cost[i−2]); answer dp[n].
Complexity: O(n) time, O(1) space.
class Solution:
def minCostClimbingStairs(self, cost: List[int]) -> int:
a = b = 0 # dp[i-2], dp[i-1]
for i in range(2, len(cost) + 1):
a, b = b, min(b + cost[i - 1], a + cost[i - 2])
return b
assert Solution().minCostClimbingStairs([10, 15, 20]) == 15
assert Solution().minCostClimbingStairs([1, 100, 1, 1, 1, 100, 1, 1, 100, 1]) == 6
class Solution {
public int minCostClimbingStairs(int[] cost) {
int a = 0, b = 0;
for (int i = 2; i <= cost.length; i++) {
int c = Math.min(b + cost[i - 1], a + cost[i - 2]);
a = b; b = c;
}
return b;
}
}
func minCostClimbingStairs(cost []int) int {
a, b := 0, 0 // dp[i-2], dp[i-1]: cheapest way to stand on step i
for i := 2; i <= len(cost); i++ {
a, b = b, min(b+cost[i-1], a+cost[i-2])
}
return b
}