Min Cost Climbing Stairs
Difficulty: Easy · Pattern: 1-D Dynamic Programming · LeetCode #746
cost[i] is the price of stepping on stair i. After paying, you can climb one or two steps. You may start at stair 0 or stair 1. Return the minimum cost to reach the top, the position just past the last stair.
Examples
text
[10,15,20] → 15 (start at 1, pay 15, jump 2 to the top)
[1,100,1,1,1,100,1,1,100,1] → 6Hints
- Define
dp[i]= the minimum cost to stand on stair i (including paying for it). - You can reach the top from either of the last two stairs.
Approach
dp[i] = cost[i] + min(dp[i−1], dp[i−2]), with dp[0] = cost[0] and dp[1] = cost[1]. The answer is min(dp[n−1], dp[n−2]).
Only the last two values are needed, so the space is O(1). This is the standard first DP to practice choosing the state: "cost to stand on i" here, versus "cost to reach i" in the alternative formulation dp[i] = min(dp[i−1] + cost[i−1], dp[i−2] + cost[i−2]). Both work.
Complexity
Time: O(n). Space: O(1).
Python solution
def minCostClimbingStairs(cost):
a, b = cost[0], cost[1]
for c in cost[2:]:
a, b = b, c + min(a, b)
return min(a, b)JavaScript solution
function minCostClimbingStairs(cost) {
let a = cost[0], b = cost[1];
for (let i = 2; i < cost.length; i++) [a, b] = [b, cost[i] + Math.min(a, b)];
return Math.min(a, b);
}