Dynamic programming
Base case: standing on step 0 costs its own price, 42.
1 / 23How min cost stairs works
You climb a staircase paying each step's cost, moving 1 or 2 steps at a time, starting from step 0 or 1, and you may finish off the end from either of the last two steps. The question “what is the cheapest way to stand on step i?” has a tiny answer: you arrived from i−1 or i−2, so it is cost[i] plus the cheaper of those two already-solved answers. That equation — the recurrence — is the entire algorithm.
This is dynamic programming with all the mystery removed: an overlapping-subproblem structure (naive recursion would recompute the same steps exponentially often) collapsed into one left-to-right pass, because by the time you reach step i, both answers it depends on are sitting in the table. Watch the dp labels fill under the bars — each one computed once, from two neighbours, never revised.
Two habits to build here that carry to every DP: read the recurrence out loud before coding (if you cannot state it, the code will not save you), and notice the space optimization — dp[i] only looks back two slots, so two variables replace the whole array, O(n) → O(1). Interviewers ask for that follow-up almost every time.
space play / pause · ←→ step
Complexity
| time | O(n) |
|---|---|
| space | O(n) → O(1) |
| recurrence | dp[i] = cost[i] + min(dp[i−1], dp[i−2]) |
| pattern | 1-D bottom-up |