Practice › Dynamic Programming
Min Cost Climbing Stairs
Easy · Dynamic Programming · Asked at Amazon, Microsoft, TCS, Infosys
Step i of a staircase costs cost[i] to stand on. You may start on step 0 or step 1. After paying for a step you climb one or two steps. Print the minimum total cost to reach the top, which is just past the last step.
Input
First line: n. Second line: n space-separated integers.
Output
The minimum cost to reach the top.
Constraints
- 2 ≤ n ≤ 10^5
- 0 ≤ cost[i] ≤ 999
dp[i] = cost[i] + min(dp[i − 1], dp[i − 2]) is the cheapest way to stand on step i. The top can be reached from either of the last two steps.
Example 1
Input
3 10 15 20
Output
15
Example 2
Input
10 1 100 1 1 1 100 1 1 100 1
Output
6
Hints
- To stand on step i you came from step i − 1 or step i − 2.
- dp[i] = cost[i] + min(dp[i − 1], dp[i − 2]).
- The top is reached from one of the last two steps.
Approach
Let dp[i] be the cheapest total to stand on step i, including its cost. dp[0] = cost[0], dp[1] = cost[1] (you may start on either). For i ≥ 2, dp[i] = cost[i] + min(dp[i − 1], dp[i − 2]). The answer is min(dp[n − 1], dp[n − 2]). Only two previous values are needed.
Complexity: O(n) time · O(1) extra space
Solution
C++ solution
#include <bits/stdc++.h>
using namespace std;
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int n;
cin >> n;
vector<long long> c(n);
for (auto &x : c) cin >> x;
long long a = c[0], b = c[1];
for (int i = 2; i < n; i++) {
long long cur = c[i] + min(a, b);
a = b;
b = cur;
}
cout << min(a, b) << "\n";
return 0;
}Python solution
import sys
data = list(map(int, sys.stdin.read().split()))
c = data[1 : 1 + data[0]]
a, b = c[0], c[1]
for x in c[2:]:
a, b = b, x + min(a, b)
print(min(a, b))Java solution
import java.io.*;
public class Main {
public static void main(String[] args) throws IOException {
StreamTokenizer in = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in)));
in.nextToken();
int n = (int) in.nval;
long[] c = new long[n];
for (int i = 0; i < n; i++) {
in.nextToken();
c[i] = (long) in.nval;
}
long a = c[0], b = c[1];
for (int i = 2; i < n; i++) {
long cur = c[i] + Math.min(a, b);
a = b;
b = cur;
}
System.out.println(Math.min(a, b));
}
}Solve Min Cost Climbing Stairs online · All practice problems