Example 1
- Input
- cost = [10, 15, 20]
- Output
- 15
Start on step 1, pay 15, then climb two steps straight to the top.
Each step charges a fee when you leave it, and from any step you may climb one or two steps forward. Starting from step 0 or step 1, find the cheapest total fee that reaches the top just past the last step.
You are given an integer array cost where cost[i] is the price you pay when you leave step i. From any step you may climb either one or two steps forward.
You may start on step 0 or step 1 without paying anything yet. Paying happens only when you leave a step you are standing on, so the starting step itself is free until you move.
Return the minimum total price needed to reach the top, which is the position just past the last index of cost (index n for an array of length n).
2 <= cost.length <= 10000 <= cost[i] <= 999Start on step 1, pay 15, then climb two steps straight to the top.
Start at index 0 and leave paid indices 0, 2, 4, 6, 7, and 9, then reach the top at 10. Their six fees are all 1; the jumps are 2, 2, 2, 1, 2, and 1. The one-step jump from 6 to 7 is necessary to skip index 8. The minimum-cost recurrence confirms that no route costs less than 6.
With only two steps, start at index 0, pay its zero fee, and jump two steps to top index 2. Starting at index 1 would pay 999, so the answer is 0. A free start does not waive a departure fee; here that fee happens to be zero.
A route pays only for the steps it leaves, so skipping an expensive step can be cheaper than taking more short moves. In [10, 15, 20], starting at step 1 and jumping to the top pays 15; starting at step 0 costs at least 25. To reach any position, the last move must come from one of its two predecessors. Compare the cheapest cost to reach each predecessor plus its departure fee. Those two choices contain every possible final move, and only their two best costs need to be remembered.
Reveal Recursive Branching: intuition, complexity, and code
i you must arrive from step i - 1 or step i - 2, so the answer for i depends only on those two earlier answers.dp[i] = min(dp[i - 1] + cost[i - 1], dp[i - 2] + cost[i - 2]) with dp[0] = dp[1] = 0, and fill it from left to right.When the best value at position i depends only on a fixed window of earlier positions, fill a 1D table left to right and then shrink the window to a few rolling variables.