Algo-Sim › Dynamic Programming

Min Cost Climbing Stairs

Easy · Dynamic Programming · step through it in Java, Python and C++ on your own input

Climbing Stairs with a price on every step: dp[i] is the cheaper of arriving from one or two steps below.

Problem

You are given cost, where cost[i] is the price of stepping off stair i. Once you pay it, you can climb one or two stairs. You may start on stair 0 or stair 1. Return the minimum cost to reach the top, the position just past the last stair.

Constraints

Edge cases to test

Follow-up questions

Why only two variables?
Each dp value depends on the two below it, so a rolling pair gives O(1) space.
How do you recover the path?
Keep the choice at each step (one or two below) and walk back from the top.

Solution

Java

public 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 min_cost_climbing_stairs(cost):
    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++

#include <bits/stdc++.h>
using namespace std;

class Solution {
  public:
    int minCostClimbingStairs(vector<int> &cost) {
        int n = int(cost.size());
        vector<int> dp = vector<int>(n + 1);
        for (int i = 2; i <= n; i++) {
            dp[i] = std::min(dp[i - 1] + cost[i - 1], dp[i - 2] + cost[i - 2]);
        }
        return dp[n];
    }
};

More Dynamic Programming problems