Problem
You are given an integer array cost
where cost[i]
is the cost of ith
step on a staircase. Once you pay the cost, you can either climb one or two steps.
You can either start from the step with index 0
, or the step with index 1
.
Return the minimum cost to reach the top of the floor.
Examples
Example 1:
Input:
cost = [10,15,20]
Output:
15
Explanation: You will start at index 1.
- Pay 15 and climb two steps to reach the top.
The total cost is 15.
Example 2:
Input:
cost = [1,100,1,1,1,100,1,1,100,1]
Output:
6
Explanation: You will start at index 0.
- Pay 1 and climb two steps to reach index 2.
- Pay 1 and climb two steps to reach index 4.
- Pay 1 and climb two steps to reach index 6.
- Pay 1 and climb one step to reach index 7.
- Pay 1 and climb two steps to reach index 9.
- Pay 1 and climb one step to reach the top.
The total cost is 6.
Solution
The greedy will not work as sometimes we will not always take 2 steps. Sometimes, 1 step also makes sense. See example 2. This problem is like an extension to Climbing Stairs Problem 1 - Take atmost 2 Steps.
Method 1 - Recursion
We start at either step 0 or step 1. The target is to reach either last or second last step, whichever is minimum.
Recurrence Relation
mincost(i) = cost[i]+min(mincost(i-1), mincost(i-2))
Base case
mincost(0) = cost[0]
mincost(1) = cost[1]
Code
Java
public int minCostClimbingStairs(int[] cost) {
int n = cost.length;
return Math.min(minCost(cost, n - 1), minCost(cost, n - 2));
}
private int minCost(int[] cost, int idx) {
if (idx < 0) {
return 0;
}
if (idx == 0 || idx == 1) {
return cost[i];
}
return cost[idx] + Math.min(minCost(cost, idx - 1), min)
}
Complexity
- ⏰ Time complexity:
O(2^n)
- 🧺 Space complexity:
O(n)
Method 2 - Top Down DP with memoization
Code
Java
public int minCostClimbingStairs(int[] cost) {
int n = cost.length;
int dp = new int[n];
return Math.min(minCost(cost, n - 1, dp), minCost(cost, n - 2, dp));
}
private int minCost(int[] cost, int idx, int[] dp) {
if (idx < 0) {
return 0;
}
if (idx == 0 || idx == 1) {
return cost[i];
}
if (dp[idx] != 0) {
return dp[idx];
}
dp[idx] = cost[idx] + Math.min(minCost(cost, idx - 1), min)
return dp[n];
}
Complexity
- ⏰ Time complexity:
O(n)
- 🧺 Space complexity:
O(n)
Method 2 - Bottom UP DP
Code
Java
public int minCostClimbingStairs(int[] cost) {
int n = cost.length;
int[] dp = new int[n];
dp[0] = cost[0];
dp[1] = cost[1];
for (int i = 2; i < n; i++) {
dp[i] = cost[i] + Math.min(dp[i - 1], dp[i - 2]);
}
return Math.min(dp[n - 1], dp[n - 2]);
}
Complexity
- ⏰ Time complexity:
O(n)
- 🧺 Space complexity:
O(n)
Method 3 - Bottom up DB without using extra space
Code
Java
public int minCostClimbingStairs(int[] cost) {
int n = cost.length;
int f1 = cost[0], f2 = cost[1];
if (n <= 2) {
return Math.min(f1, f2);
}
for (int i = 2; i < n; i++) {
int curr = cost[i] + Math.min(f1, f2);
f1 = f2;
f2 = temp;
}
return Math.min(f1, f2);
}
Complexity
- ⏰ Time complexity:
O(n)
- 🧺 Space complexity:
O(1)