Min Cost Climbing Stairs

easy1D Dynamic Programming23 stepsJava · Python · C++

Each step has a cost to step on; you can start at step 0 or 1 and climb 1 or 2 at a time. The cheapest way to reach step i is min(dp[i−1] + cost[i−1], dp[i−2] + cost[i−2]). The top is one past the last step.

▶ Watch the animated trace

Traced input: cost = [1, 100, 1, 1, 1, 100, 1, 1, 100, 1] → 6. Original problem: neetcode.io/problems/min-cost-climbing-stairs

Complexity

BestO(n)
AverageO(n)
WorstO(n)
SpaceO(n)

Can be reduced to O(1) with two variables.

Key idea

Common mistakes

Solution

Java
int minCostClimbingStairs(int[] cost) {
    int n = cost.length;
    int[] dp = new int[n + 1];
    for (int i = 2; i <= n; i++) {
        dp[i] = Math.min(dp[i - 1] + cost[i - 1], dp[i - 2] + cost[i - 2]);
    }
    return dp[n];
}
Python
def minCostClimbingStairs(cost: List[int]) -> int:
    n = len(cost)
    dp = [0] * (n + 1)
    for i in range(2, n + 1):
        dp[i] = min(dp[i - 1] + cost[i - 1], dp[i - 2] + cost[i - 2])
    return dp[n]
C++
int minCostClimbingStairs(vector<int>& cost) {
    int n = cost.size();
    vector<int> dp(n + 1);
    for (int i = 2; i <= n; i++) {
        dp[i] = min(dp[i - 1] + cost[i - 1], dp[i - 2] + cost[i - 2]);
    }
    return dp[n];
}

Edge cases

Each one has its own trace in the interactive view.

CaseInputAnswer
Two steps
Start on step 0 and jump 2.
cost = [10, 15]10
Three steps
Start on step 1 and jump 2.
cost = [10, 15, 20]15
Zero costs
Free all the way.
cost = [0, 0, 0]0
← Climbing StairsHouse Robber →