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.
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.
Constraints:
-
2 <= cost.length <= 1000
-
0 <= cost[i] <= 999
Approach 1
Let dp[i] be the cost to climb the i-th staircase to from 0-th or 1-th step. Hence dp[i] = cost[i] + min(dp[i-1], dp[i-2]). Since dp[i-1] and dp[i-2] are needed to compute the cost of traveling from i-th step, a bottom-up approach can be used to solve the problem.
The answer will be the minimum cost of reaching n-1th stair and n-2th stair. Compute the dp[] array in a bottom-up manner.
Below is the implementation of the above approach.
import java.io.*; import java.util.*; class Techtwitter { // function to find // the minimum cost // to reach N-th floor static int minimumCost(int cost[], int n) { // declare an array int dp[] = new int[n]; // base case if (n == 1) return cost[0]; // initially to // climb till 0-th // or 1th stair dp[0] = cost[0]; dp[1] = cost[1]; // iterate for finding the cost for (int i = 2; i < n; i++) { dp[i] = Math.min(dp[i - 1], dp[i - 2]) + cost[i]; } // return the minimum return Math.min(dp[n - 2], dp[n - 1]); } // Driver Code public static void main(String args[]) { int a[] = { 16, 19, 10, 12, 18 }; int n = a.length; System.out.print(minimumCost(a, n)); } }
31
Time Complexity: O(N)
Auxiliary Space: O(N)
Space-optimized Approach 4: Instead of using dp[] array for memoizing the cost, use two-variable dp1 and dp2. Since the cost of reaching the last two stairs is required only, use two variables and update them by swapping when one stair is climbed.
Below is the implementation of the above approach:
import java.io.*; import java.util.*; class Techtwitter { // function to find // the minimum cost // to reach N-th floor static int minimumCost(int cost[], int n) { int dp1 = 0, dp2 = 0; // traverse till N-th stair for (int i = 0; i < n; i++) { int dp0 = cost[i] + Math.min(dp1, dp2); // update the last // two stairs value dp2 = dp1; dp1 = dp0; } return Math.min(dp1, dp2); } // Driver Code public static void main(String args[]) { int a[] = { 2, 5, 3, 1, 7, 3, 4 }; int n = a.length; System.out.print(minimumCost(a, n)); } }