progress

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

Cheapest climb with strides of one to three steps

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

easy ~15 min

A staircase has steps 0 .. len(toll) - 1; landing on step i costs toll[i]. You start on the ground below step 0 and want the landing above the last step. Each move goes up 1, 2 or 3 positions. The ground and the landing are free.

Write min_toll_climb(toll: list[int]) -> int: the smallest total toll for the climb.

min_toll_climb([4, 9, 2, 8, 7, 1])  # 3    ground -> step 2 -> step 5 -> landing
min_toll_climb([5, 5, 5, 5])        # 5    ground -> step 1 -> landing
min_toll_climb([7, 3])              # 0    stride straight over both steps
min_toll_climb([])                  # 0

Up to 10^5 steps, tolls up to 10^4.

⭐ Bonus: a speed test with 100,000 steps earns a star in O(n) time and O(1) extra space. Trying every route is exponential, and a recursive search one step per call runs out of stack there.

Show hint

The cheapest way to land on step i depends only on the three steps just below it.

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