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.
1public class Solution {
2 public int MinCostClimbingStairs(int[] cost) {
3 int n = cost.Length;
4 int[] dp = new int[n + 1];
5 dp[0] = cost[0];
6 dp[1] = cost[1];
7 for (int i = 2; i < n; i++) {
8 dp[i] = Math.Min(dp[i - 1], dp[i - 2]) + cost[i];
9 }
10 return Math.Min(dp[n - 1], dp[n - 2]);
11 }
12}
The C# solution follows a similar logic, creating an array dp. It iteratively determines the minimum cost to reach each step by leveraging previously computed costs and the current cost value.
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)
1var minCostClimbingStairs = function(cost) {
2 let prev = cost[0], curr = cost[1];
3 for (let i = 2; i < cost.length; i++) {
4 let next = Math.min(prev, curr) + cost[i];
5 prev = curr;
6 curr = next;
7 }
8 return Math.min(prev, curr);
9};
The JavaScript solution employs two numeric variables, prev and curr, to track costs efficiently through iteration. These values are adjusted with each step using the cost array, ultimately providing a streamlined approach for solving the problem within constant space.