Skip to content
Work Practice Products Coding interviews Machine learning coding Quant developer HFT course Blog Method Why me About Enquire Book a call

Coding · Dynamic programming

The cheapest way up a staircase

Easy · Target 10 minutes · Dynamic programming · Type asked atAmazon

cost[i] is the cost of standing on step i. You may start on step 0 or step 1, and from any step you climb one or two steps. Return the minimum total cost to get past the last step (to position n).

Examples

InputOutputWhy
cost = [10,15,20]15Start on step 1 and climb two.
cost = [1,100,1,1,1,100,1,1,100,1]6Avoid every 100.
cost = [0,0]0Free.

Constraints

  • 2 ≤ cost.length ≤ 1000
  • 0 ≤ cost[i] ≤ 999

Hints

Hint 1

To stand on step i you came from i − 1 or i − 2.

Hint 2

dp[i] = cost[i] + min(dp[i − 1], dp[i − 2]); dp[0] = cost[0], dp[1] = cost[1].

Hint 3

The top is reached from the last or second-to-last step: min(dp[n − 1], dp[n − 2]).

Where people lose marks

  • Returning dp[n − 1] only: the top can be reached from step n − 2 as well.
  • Forgetting that the start can be step 1, which makes dp[1] = cost[1] rather than cost[0] + cost[1].
Console⌘/Ctrl + Enter runs

Write a solution and run it against the real test table.


Keep going

Preparing for a real process? Quant interview preparation, or book a free 20-minute call.