Problem
Given an integer array cost, wherecost[i] represents the cost of stepping on the ith stair, you can start from either step 0 or step 1.
At each step, you can climb either one or two stairs. Return the minimum cost required to reach the top of the staircase.
You do not have to pay the cost of the top because it is beyond the last stair.
Example(s)
Example 1
Input
cost = [10,15,20]
Output
15
Example 2
Input
cost = [1,100,1,1,1,100,1,1,100,1]
Approach 1: Memoization
This problem can be solved using Dynamic Programming with Memoization. At each stair, we have two choices: climb one step or climb two steps.For each step, we recursively calculate the minimum cost of reaching the top. The result for each step is stored in a
memo array so that the same subproblem is not calculated again.
When we reach or pass the top of the staircase, no additional cost is required. Therefore, the minimum cost from a step is the cost of that step plus the minimum cost of taking either one or two steps.
class Solution {
public int minCostClimbingStairs(int[] cost) {
Integer[] memo = new Integer[cost.length];
return Math.min(
minCostClimbingStairs(0, cost, memo),
minCostClimbingStairs(1, cost, memo)
);
}
private int minCostClimbingStairs(
int step, int[] cost, Integer[] memo) {
if (step >= cost.length) {
return 0;
}
if (memo[step] != null) {
return memo[step];
}
return memo[step] = cost[step] +
Math.min(
minCostClimbingStairs(step + 1, cost, memo),
minCostClimbingStairs(step + 2, cost, memo)
);
}
}
Approach 2: Space Optimized Dynamic Programming
The memoization approach stores the result for every step. However, we can solve the problem iteratively by keeping only the minimum costs of the previous two steps.This reduces the extra space complexity from
O(n) to O(1).
class Solution {
public int minCostClimbingStairs(int[] cost) {
int prev2 = cost[0];
int prev1 = cost[1];
for (int i = 2; i < cost.length; i++) {
int current = cost[i] + Math.min(prev1, prev2);
prev2 = prev1;
prev1 = current;
}
return Math.min(prev1, prev2);
}
}
Complexity
For the Memoization approach, each step is calculated only once, so the time complexity isO(n). The memoization array and recursion stack require O(n) extra space.
For the Space Optimized approach, each step is processed once, giving a time complexity of
O(n). Only a few variables are used, so the extra space complexity is O(1).
Comments
No comments yet. Ask a question or share what helped.