Min cost climbing stairs
Cheapest way to reach the top of a staircase, paying the cost of a step each time you leave it, moving 1 or 2 steps at a time.
Watch it animatedStep through it, with the running line highlighted. Free, no sign-in needed to watch.The idea
The top is one step past the last stair, and you may start free on step 0 or step 1. The cheapest cost to reach step i comes from paying to leave step i-1 or step i-2, whichever is cheaper. Only the last two costs are read, so two variables replace the table.
Code
public static int MinCostClimbingStairs(int[] cost) {
int prev2 = 0, prev1 = 0;
for (int i = 2; i <= cost.Length; i++) {
int cur = Math.Min(prev1 + cost[i - 1], prev2 + cost[i - 2]);
prev2 = prev1; prev1 = cur;
}
return prev1;
}static int minCostClimbingStairs(int[] cost) {
int prev2 = 0, prev1 = 0;
for (int i = 2; i <= cost.length; i++) {
int cur = Math.min(prev1 + cost[i - 1], prev2 + cost[i - 2]);
prev2 = prev1; prev1 = cur;
}
return prev1;
}int minCostClimbingStairs(const vector<int>& cost) {
int prev2 = 0, prev1 = 0;
for (int i = 2; i <= (int)cost.size(); i++) {
int cur = min(prev1 + cost[i - 1], prev2 + cost[i - 2]);
prev2 = prev1; prev1 = cur;
}
return prev1;
}def min_cost_climbing_stairs(cost: list[int]) -> int:
prev2, prev1 = 0, 0
for i in range(2, len(cost) + 1):
cur = min(prev1 + cost[i - 1], prev2 + cost[i - 2])
prev2, prev1 = prev1, cur
return prev1Tips
- Both starting values are 0: you may begin the climb at either step without charge.
- Write the table version first if it helps, then keep only the last two cells.
In the .NET library
The cost is charged when you leave a step, not when you land on it. That is why the formula adds cost[i-1] or cost[i-2], the step being left.