Skip to content
Problem 746 · LeetCode 746(opens in a new tab)

Min Cost Climbing Stairs

EasyArrays

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.

Try it on LeetCode(opens in a new tab)
  1. Recursion with a memoO(n)
  2. Bottom-up tableO(n)
  3. Two variablesO(n)

The idea in one sentence

The pattern, how to spot it, and the best complexity.

Side by side

ApproachTimeRelative work for 1,000 stepsVerdict
Recursion with a memoO(n)
Passes; deep call stack
Bottom-up tableO(n)
Passes; O(n) memory
Two variablesO(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

  1. 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?
  2. 2Define the subproblem. Cheapest way to stand on step i. It comes from i − 1 or i − 2.
  3. 3Give the memo version. Write the recursion and add a memo. Say plain recursion would be O(2ⁿ).
  4. 4Turn it bottom-up, then shrink. Fill a table from step 2; then notice only two cells are read, and keep two variables.
  5. 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?