Min Cost Climbing Stairs – Solution & Complexity
Solution Walkthrough
Step 1: Frame the recurrence
- Let
best[i]be the cheapest toll paid to arrive at stairi. - Arriving at the top means arriving at index
n, one past the last stair. - You reach stair
ifrom either stairi-1or stairi-2, paying that stair's toll when you leave it.
- Let
Step 2: Tabulate over a DP array
best[0] = best[1] = 0because you may start on either stair for free.- For every later index, take the cheaper of the two incoming moves and add the toll you paid to make that move.
- The answer is
best[n].
Step 3: Collapse to two rolling variables
- The recurrence only ever looks back two positions, so a full array is unnecessary.
- Track
downOne(cost to reach the previous stair) anddownTwo(the stair before that) and slide them forward.
Step 4: Optimal O(1)-space scan
- Iterate from index
2throughn, computing each new arrival cost from the two rolling variables, then shift them. - After the loop,
downOneholds the cost to reach the top.
- Iterate from index
Step 5: Dry run
Trace
cost = [10,15,20].i downTwo downOne new step 2 0 0 min(0+15, 0+10) = 10 3 0 10 min(10+20, 0+15) = 15 The loop ends with
downOne = 15, matching the expected answer.Step 6: Common mistakes and follow-ups
- Returning
dp[n-1]instead ofdp[n], which stops one stair short of the top. - Adding
cost[i]when arriving instead ofcost[i-1]/cost[i-2]for the stair you leave. - Forgetting that both stair
0and stair1are free starting points. - Follow-up: how would the recurrence change if you could also climb three stairs at a time?
- Returning
Step 7: Edge cases to test mentally
- The minimum length is
2; the answer is thenmin(cost[0], cost[1]). - All-zero tolls cost
0. - Alternating free and expensive stairs should always land on the free ones.
- The minimum length is
Step 8: Final full solution and complexity
A single left-to-right scan keeps two rolling subresults. Time is
O(n)and extra space isO(1).