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
- 2 ≤ cost.length ≤ 1000
- 0 ≤ cost[i] ≤ 999
- The top is index n, one past the last stair
Edge cases to test
- Two steps only
- All costs zero
- The top is past the last step (it costs nothing)
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
- Climbing Stairs: Recursion → Memo → Table (Easy)
- House Robber (Medium)
- House Robber II (Medium)
- Coin Change (Medium)
- Coin Change II (Medium)
- Perfect Squares (Medium)
- Combination Sum IV (Medium)
- Decode Ways (Medium)
- Maximum Product Subarray (Medium)
- Best Time to Buy and Sell Stock with Cooldown (Medium)
- Best Time to Buy and Sell Stock with Transaction Fee (Medium)
- Best Time to Buy and Sell Stock III (Hard)
- Longest Increasing Subsequence (Medium)
- Word Break (Medium)
- Unique Paths (Medium)
- Unique Paths II (Medium)
- Minimum Path Sum (Medium)
- Maximal Square (Medium)
- Partition Equal Subset Sum (Medium)
- Target Sum (Medium)
- Longest Common Subsequence (Medium)
- Interleaving String (Medium)
- 0/1 Knapsack (Medium)
- Edit Distance (Medium)
- Distinct Subsequences (Hard)
- Longest Palindromic Substring (Medium)
- Palindromic Substrings (Medium)
- Longest Palindromic Subsequence (Medium)
- Predict the Winner (Medium)
- Stone Game (Medium)