A staircase has steps numbered from 0, and cost[i] is the fee for leaving step i. Once you pay a step's fee you move up one step or two. You may begin on step 0 or on step 1, for free.
The top is just past the last step, at index cost.length. Return the smallest total fee that gets you there.
Example 1
Input: cost = [4, 9, 3, 7] Output: 7 Why: start on step 0, pay 4 to jump to step 2, pay 3 to jump to the top
2 more examples and the constraints
Example 2
Input: cost = [1, 50, 1, 50, 1, 1, 50, 1] Output: 5 Why: step on 0, 2, 4, 5 and 7, paying 1 each time; never touch a 50
Example 3
Input: cost = [0, 0] Output: 0 Why: start on step 1 and jump to the top for free
Constraints
- 2 ≤ length of cost ≤ 1,000
- 0 ≤ cost[i] ≤ 999
Your turn first
Have a go on paper or in your own editor, then reveal the approaches from the simplest up.
- Recursion with a memoO(n)
- Bottom-up tableO(n)
- Two variablesO(n)
The idea in one sentence
The pattern, how to spot it, and the best complexity.
Side by side
| Approach | Time | Relative work for 1,000 steps | Verdict |
|---|---|---|---|
| Recursion with a memo | O(n) | Passes; deep call stack | |
| Bottom-up table | O(n) | Passes; O(n) memory | |
| Two variables | O(n) | Best; constant memory |
n = number of steps. All three are linear; the work differs by call and memo overhead.
Edge cases to test
- Only two steps. [5, 3]: start on step 1 and pay 3 to reach the top.
- Free steps. [0, 0] costs 0; zero fees are allowed.
- The top is not a step. Index n has no fee. The answer is the cost to stand there, not the cost of a last step.
- Skipping the last step. In [4, 9, 3, 7] the 7 is never paid: from step 2 you jump straight to the top.
Common mistakes
- Returning dp[n − 1], which stands on the last step instead of past it.
- Paying the fee of the step you land on instead of the one you leave.
- Making step 0 cost cost[0] up front, forgetting that you may also start on step 1 for free.
How to talk through it
- 1Clarify. Is the top past the last step? Do I pay for the step I leave or the one I land on? Can a fee be 0?
- 2Define the subproblem. Cheapest way to stand on step i. It comes from i − 1 or i − 2.
- 3Give the memo version. Write the recursion and add a memo. Say plain recursion would be O(2ⁿ).
- 4Turn it bottom-up, then shrink. Fill a table from step 2; then notice only two cells are read, and keep two variables.
- 5Test out loud. Run [4, 9, 3, 7] and a two-step input before saying you are done.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?