Min Cost Climbing Stairs
easy 16 minEach step has a toll; you may start on step 0 or 1, pay for every step you stand on, and climb one or two at a time.
Video lesson · Chapter 1 of 6
The exit has no price tag
Min cost climbing stairs in 75 seconds
1:26Reel
How it works
Step through the idea, or press Play.
Define the state. dp[i] = the cheapest total having paid for step i; you may start on step 0 or step 1
Understand it
Start here
A staircase with a toll on every step
You get a list cost where cost[i] is the toll for standing on step . After paying, you climb 1 or 2 steps. You may begin on step 0 or step 1, and you want to reach the top for the smallest total toll. Our first example is cost = [10, 15, 20].
| index | 0 | 1 | 2 | 3 |
|---|---|---|---|---|
| what it is | step | step | step | top |
| toll | 10 | 15 | 20 | free |
It is Climbing stairs with prices: the same 1-or-2 moves, but instead of counting ways we look for the cheapest one. If dynamic programming is new, start with Dynamic programming basics.
The rules
Four rules that shape the answer
Start on 0 or 1
Nothing below your starting step is paid. So the cheapest way onto step 1 is just
cost[1].Pay where you stand
Every step you land on charges its toll. Steps you hop over cost nothing.
Move 1 or 2
From step you go to or , so step is entered from or .
The top is free
Index has no toll. Reaching it ends the climb.
The moves around step i
Optimisation: min cost
- Input: a list of tolls
cost. - Combine the two options with min.
- dp[i] = cost[i] + min(dp[i - 1], dp[i - 2]).
Counting: climbing stairs
- Input: just the number of steps n.
- Combine the two options with +.
- ways[i] = ways[i - 1] + ways[i - 2].
The state
Two ways to define dp
There are two common definitions. Both are correct, and both give the same answer. Pick one and stick to it; this topic, its visualizer and its code all use the first.
Paid for step i (used here)
Arrived at step i, toll not yet paid
The recurrence
Pay here, plus the cheaper way in
The full recurrence
Filling one cell
For [10, 15, 20]: dp[0] = 10, dp[1] = 15, dp[2] = 20 + min(15, 10) = 30. The answer is . Notice that greedy, which starts on the cheaper step 0 and then picks the cheaper next step, pays .
Brute force
Plain recursion and its repeated work
def min_cost_brute(cost): def f(i): # cheapest total having paid for step i if i <= 1: return cost[i] # start on step 0 or step 1 return cost[i] + min(f(i - 1), f(i - 2)) n = len(cost) return min(f(n - 1), f(n - 2)) # the top is one or two hops awayprint(min_cost_brute([10, 15, 20])) # 15print(min_cost_brute([1, 100, 1, 1, 100])) # 3Calls for cost = [1, 100, 1, 1, 100]
f for 5 distinct steps. The red calls repeat work already done: overlapping subproblems.How many calls?
Fix 1
Memoisation: each step once
Only different questions exist, f(0) to f(n - 1). Store each answer the first time it is computed and look it up after that. The repeated subtrees above each become one lookup: 14 calls drop to 8, and in general to .
A memoised call
from functools import cachedef min_cost_memo(cost): @cache def f(i): if i <= 1: return cost[i] return cost[i] + min(f(i - 1), f(i - 2)) n = len(cost) return min(f(n - 1), f(n - 2))print(min_cost_memo([1, 100, 1, 1, 1, 100, 1, 1, 100, 1])) # 6@cache does the lookup and the store. Defining f inside keeps the cache fresh for each input.Fix 2
Tabulation: fill dp left to right
| i | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 |
|---|---|---|---|---|---|---|---|---|---|---|
cost[i] | 1 | 100 | 1 | 1 | 1 | 100 | 1 | 1 | 100 | 1 |
dp[i] | 1 | 100 | 2 | 3 | 3 | 103 | 4 | 5 | 104 | 6 |
- 1Cost array[1, 100, 1, ...]
- 2Base casesdp[0], dp[1]
- 3Build dpcost[i] + min of two
- 4Find minmin(dp[n-1], dp[n-2])
- 5Result6
def min_cost_table(cost): n = len(cost) if n < 2: return 0 # one step: start on step 1, which is the top dp = [0] * n dp[0], dp[1] = cost[0], cost[1] for i in range(2, n): dp[i] = cost[i] + min(dp[i - 1], dp[i - 2]) return min(dp[n - 1], dp[n - 2])print(min_cost_table([10, 15, 20])) # 15print(min_cost_table([1, 100, 1, 1, 1, 100, 1, 1, 100, 1])) # 6Fix 3
O(1) space with a rolling pair
The loop reads only dp[i - 1] and dp[i - 2]. Keep them in two variables, prev1 and prev2, and slide the pair one step after each cell. Time stays ; space drops to .
def min_cost(cost): prev2, prev1 = cost[0], cost[1] # dp[i - 2], dp[i - 1] for i in range(2, len(cost)): cur = cost[i] + min(prev1, prev2) prev2, prev1 = prev1, cur # slide the pair return min(prev1, prev2)print(min_cost([1, 2, 3, 4, 5])) # 6print(min_cost([5, 1, 5, 1, 5])) # 2Which steps?
Reconstructing the cheapest path
The table knows more than the total. Start at the top, step back to whichever of the last two cells is cheaper, and keep stepping back to the cheaper predecessor until you reach step 0 or 1. Reverse the list.
Walking the table backwards
def cheapest_path(cost): n = len(cost) dp = cost[:2] + [0] * (n - 2) for i in range(2, n): dp[i] = cost[i] + min(dp[i - 1], dp[i - 2]) i = n - 1 if dp[n - 1] <= dp[n - 2] else n - 2 path = [i] while i > 1: i = i - 1 if dp[i - 1] <= dp[i - 2] else i - 2 path.append(i) return path[::-1]cost = [1, 100, 1, 1, 1, 100, 1, 1, 100, 1]p = cheapest_path(cost)print(p, sum(cost[i] for i in p)) # [0, 2, 4, 6, 7, 9] 6Comparison
Every approach side by side
| Approach | Time | Space | Notes |
|---|---|---|---|
| Greedy (cheaper next step) | Wrong: [10, 15, 20] gives 25, not 15 | ||
| Plain recursion | , so | stack | Fixes the meaning of f(i); too slow past about 30 steps |
| Memoised recursion | memo + stack | Quick to write; recursion limit for long inputs | |
| Table (bottom-up) | Keeps every value, so the path can be rebuilt | ||
| Rolling pair | The usual final answer |
| Aspect | Climbing stairs | Min cost climbing |
|---|---|---|
| Goal | Count the ways | Minimise the total cost |
| Operation | Addition (+) | Minimum (min) |
| Recurrence | ways[i-1] + ways[i-2] | cost[i] + min(dp[i-1], dp[i-2]) |
| Input | n, the number of steps | cost[], a toll per step |
| Type | Counting problem | Optimisation problem |
Pattern spotting
Where this shape shows up again
Is it this pattern?
House robber
Take house plus the best up to , or skip it: instead of . See House robber.
Jump game II
Fewest jumps to the end when each cell says how far you may jump: the same "best way in" idea over a wider window.
Delete and earn, paint house
Pick values along a line with a rule about neighbours. One row of DP, a min or a max, the last two or three cells.
Recap
Key takeaways
Key points
- You pay the toll of every step you stand on, start on step 0 or 1, and climb 1 or 2.
- The top is index n, past the last step, so the answer is min(dp[n - 1], dp[n - 2]).
- dp[i] = cost[i] + min(dp[i - 1], dp[i - 2]) with dp[0] = cost[0] and dp[1] = cost[1].
- The other definition, r[i] = cost to arrive at i, ends at r[n]. Pick one and do not mix them.
- Plain recursion is Θ(φⁿ); memoisation and tabulation are O(n); a rolling pair is O(1) space.
- Greedy fails: [10, 15, 20] costs 25 greedily but 15 at best.
- Keep the table and walk back to the cheaper predecessor to recover the path.