progress

~/problems / 1-D dynamic programming / Intro DP

Cheapest way up a staircase

On a phone? Coding is easier on a laptop: email this problem to yourself . Meanwhile: quiz this topic or fight a boss.

easy basics ~10 min

Step i of a staircase has a toll cost[i], paid when you land on it. You start on step 0 or step 1 (paying its toll) and move up 1 or 2 steps at a time. The top is just past the last step, and reaching it is free.

Implement min_cost_climb(cost: list[int]) -> int: the smallest total toll to reach the top.

min_cost_climb([5, 2, 8])             # 2   start on step 1 (pay 2), jump 2 to the top
min_cost_climb([1, 50, 1, 1, 50, 1])  # 4   steps 0 -> 2 -> 3 -> 5 -> top

Up to 1000 steps, tolls up to 1000. With zero or one step, the answer is 0.

⭐ Bonus: a speed test with 30 steps earns a star if each step's answer is worked out once. Plain recursion makes about 2^30 calls there.

Show hint

best[i] = cost[i] + min(best[i-1], best[i-2]) is the cheapest way to land on step i; the answer is the cheaper of the last two. Two running values are enough.

Topic: Intro DP. State, transition, base case; top-down memo vs bottom-up table.

Read the visual guide
0:00
Ctrl ' run · Ctrl ↵ submit
esc