This approach uses a dynamic programming table to store the minimum cost at each step. The key idea is that to reach step i, you can come from step i-1 or step i-2, and you need to pay the cost associated with landing on step i. Thus, the cost to reach step i is the minimum of the cost to reach steps i-1 or i-2 plus cost[i]. The solution returns the minimum cost to reach the top from the last two steps.
Time Complexity: O(n), where n is the number of steps as we traverse the list once.
Space Complexity: O(n), as we need an additional array to store minimum costs at each step.
1var minCostClimbingStairs = function(cost) {
2 const n = cost.length;
3 const dp = new Array(n + 1);
4 dp[0] = cost[0];
5 dp[1] = cost[1];
6 for (let i = 2; i < n; i++) {
7 dp[i] = Math.min(dp[i - 1], dp[i - 2]) + cost[i];
8 }
9 return Math.min(dp[n - 1], dp[n - 2]);
10};
In JavaScript, an array dp holds minimum cost values using similar logic as other solutions. It processes each step's cost taking into consideration the two previous steps, storing the result in the array. The function returns the minimal cost obtained by comparing the final two positions.
This approach optimizes the space usage of the dynamic programming solution by only retaining two variables to store the minimal costs for the last two steps, instead of an entire table. This is possible because each step's cost only depends on the previous two calculations. You update these two variables iteratively to find the minimum cost to reach the top.
Time Complexity: O(n)
Space Complexity: O(1)
1public class Solution {
2 public int MinCostClimbingStairs(int[] cost) {
3 int prev = cost[0], curr = cost[1];
4 for (int i = 2; i < cost.Length; i++) {
5 int next = Math.Min(prev, curr) + cost[i];
6 prev = curr;
7 curr = next;
8 }
9 return Math.Min(prev, curr);
10 }
11}
In the C# implementation, two variables, prev and curr, are used to minimize the cost calculation. This results in an efficient solution that calculates the minimum cost by maintaining variables through iteration, ultimately providing an optimized way to get the minimum cost with minimal space usage.