Intuition
The cheapest way to reach a step comes from one of the three steps below it, so build the answer from step 0 upward.
Explanation
Idea
Let best[j] be the minimum total cost to be standing on step j. You start on step 0 for free, so best[0] = 0. Every other step j must be reached by a single jump from step j-1, j-2, or j-3 (those are the only steps a jump of length 1, 2, or 3 can come from). A jump from step i to step j costs costs[j] + (j - i)^2. That is the price of landing on step j plus the square of how far you jumped. So:
best[j] = min over i in {j-1, j-2, j-3} of ( best[i] + costs[j] + (j - i)^2 )
Because best[j] only depends on the three steps below it, filling the table left to right means every value it needs is already known. (Here costs is 1-indexed as in the statement, i.e. the cost of step j is the j-th cost.)
Walk-through: n = 4, costs = [1, 2, 3, 4]
Step costs are costs[1]=1, costs[2]=2, costs[3]=3, costs[4]=4.
- best[0] = 0: you begin here with no cost.
- best[1]: only step 0 is below it.
best[0] + 1 + 1^2 = 0 + 1 + 1 = 2. - best[2]: from step 1 →
2 + 2 + 1 = 5; from step 0 →0 + 2 + 4 = 6. Minimum is 5. - best[3]: from step 2 →
5 + 3 + 1 = 9; from step 1 →2 + 3 + 4 = 9; from step 0 →0 + 3 + 9 = 12. Minimum is 9. - best[4]: from step 3 →
9 + 4 + 1 = 14; from step 2 →5 + 4 + 4 = 13; from step 1 →2 + 4 + 9 = 15. Minimum is 13.
The answer is best[4] = 13, matching the path 0 → 1 → 2 → 4.
Complexity
- Time: O(n). Each step examines at most three predecessors, a constant amount of work.
- Space: O(n) for the table, which can be reduced to O(1) by keeping only the last three values.
Implementation
class Solution {
public int climbStairs(int n, int[] costs) {
int[] dp = new int[n + 1];
dp[0] = 0;
for (int j = 1; j <= n; j++) {
long best = Long.MAX_VALUE;
for (int i = Math.max(0, j - 3); i < j; i++) {
long cost = (long) dp[i] + costs[j - 1] + (long) (j - i) * (j - i);
if (cost < best) best = cost;
}
dp[j] = (int) best;
}
return dp[n];
}
}