The problem, in one line. Each step has a price you pay when you leave it by climbing, you may start on step 0 or 1 and hop one or two, and you want the cheapest way to get past the last step. LeetCode 746.
The tell. The same one-or-two hop as counting stairs, but the question is “cheapest”, not “how many”. When a count turns into a best value, the plus becomes a min.
The wrong first idea
Always hop to the cheaper of the next two steps.
i, total = 0, 0
while i < len(cost):
total += cost[i]
nxt = cost[i + 1] if i + 1 < len(cost) else 0
after = cost[i + 2] if i + 2 < len(cost) else 0
i += 1 if nxt <= after else 2
Looking only one hop ahead is greedy, and greedy loses. On the prices 1, 100, 1, 1, 1, 100, 1, 1, 100, 1 it pays 7 where 6 is possible. A cheap step next door can lead into a run of expensive ones, while skipping it lands you on a cheap stretch. The right answer needs the best of the whole climb behind each step, not a glance forward.
The invariant
Let b be the cheapest total to stand on the current step, not yet paying for it. To stand on step i you came from step i-1 and paid its price, or from step i-2 and paid its price.
flowchart LR A["step i-2<br/>best a"] -->|"pay cost[i-2]"| C["step i<br/>best = min"] B["step i-1<br/>best b"] -->|"pay cost[i-1]"| C
The sentence that stays true every step: a and b are the cheapest ways to arrive on the last two steps. The top is the position one past the last step.
The solution
def min_cost(cost):
a = b = 0 # cheapest way to stand on step 0 and step 1
for i in range(2, len(cost) + 1):
a, b = b, min(b + cost[i - 1], a + cost[i - 2]) # pay for the step you left
return b
print(min_cost([10, 15, 20]))
print(min_cost([1, 100, 1, 1, 1, 100, 1, 1, 100, 1]))
print(min_cost([5, 5]))
15
6
5
func minCostClimbingStairs(cost []int) int {
a, b := 0, 0 // cheapest way to stand on step 0 and step 1
for i := 2; i <= len(cost); i++ {
a, b = b, min(b+cost[i-1], a+cost[i-2]) // pay for the step you left
}
return b
}
Same three calls print 15, 6, 5.
Complexity
- Time O(n): one comparison per step.
- Space O(1): two running values.
Traps
- Answering with the cost to land on the last step. For
[10, 15, 20]that gives 10, but the top is one past the last step and the answer is 15. - Paying for the step you arrive on instead of the one you leave. For
[5, 5]that charges 10 instead of 5. - Forcing a start on step 0.
[100, 1, 100]costs 1 by starting on step 1, and a forced start pays 100 or more.
Next in the ladder
House Robber drops the price of a step and swaps it for a rule: you may take a house or skip it, but never two neighbours.