Python coding

Cheapest climb up the stairs

A staircase has steps 0 to n - 1, and landing on step i costs cost[i]. You start on the floor just below step 0 and want to reach the top, just above the last step; the floor and the top are free. Each move climbs one or two positions. Return the minimum total cost to reach the top.

cost may be empty and its values are non-negative. Aim for O(1) extra space.

Besides the tests, one large input (31 steps) with a ~200 ms limit (scaled to your device's speed): brute force won't pass.

  • min_climb_cost([3,9,4]) → 7
  • min_climb_cost([1,2,100,1]) → 3
  • min_climb_cost([2,50,2,2,50,2,50,2]) → 10
Ctrl/⌘ + Enter runs · Tab indents
Hint 1

Let best[i] be the cheapest total to land on step i. You can only arrive there from step i − 1 or step i − 2.

Hint 2

best[i] = cost[i] + min(best[i - 1], best[i - 2]), with the floor at 0. The top is reached from one of the last two steps, so two running values are enough.

Solution and why it works
pythonO(n) · O(1)
def min_climb_cost(cost: list[int]) -> int:
    two_below = one_below = 0            # best totals for the two positions under the next step
    for c in cost:
        two_below, one_below = one_below, c + min(two_below, one_below)
    return min(two_below, one_below)     # the top is one or two moves above these

Every route onto step i comes from i − 1 or i − 2, and the cheapest one reuses the cheapest routes to those two: optimal substructure with overlapping subproblems. Plain recursion recomputes them exponentially; two running values give O(n) time and O(1) space. Greedy fails: always stepping onto the cheaper of the next two pays 4 on [1, 2, 100, 1], while skipping step 0 pays 3. Read the answer from both of the last two steps, not just the last.

Related lab: Big-O growth