|
| 1 | +/* |
| 2 | + * Problem: 746 |
| 3 | + * Name: Min Cost Climbing Stairs |
| 4 | + * Difficulty: Easy |
| 5 | + * Topic: Dynamic Programming 1D |
| 6 | + * Link: https://leetcode.com/problems/ |
| 7 | + */ |
| 8 | + |
| 9 | +#include <bits/stdc++.h> |
| 10 | +using namespace std; |
| 11 | + |
| 12 | +// Storing the minimum values for each of the steps |
| 13 | +// Time Complexity: O(n) |
| 14 | +// Space Complexity: O(n) |
| 15 | +int minCostClimbingStairsMemo(vector<int>& cost) { |
| 16 | + if (cost.size() < 2) {return 0;} |
| 17 | + vector<int> minStepCost(cost.size()+1, 0); |
| 18 | + for (int step = 2; step <= cost.size(); step++){ |
| 19 | + minStepCost[step] = min(minStepCost[step-2] + cost[step-2], minStepCost[step-1] + cost[step-1]); |
| 20 | + } |
| 21 | + return minStepCost[cost.size()]; |
| 22 | +} |
| 23 | + |
| 24 | +// Storing the minimum values of the previous two steps |
| 25 | +// Time Complexity: O(n) |
| 26 | +// Space Complexity: O(1) |
| 27 | +int minCostClimbingStairsMemoPrevious(vector<int>& cost) { |
| 28 | + if (cost.size() < 2) {return 0;} |
| 29 | + vector<int> minStepCost(2, 0); |
| 30 | + for (int step = 2; step <= cost.size(); step++){ |
| 31 | + minStepCost[step % 2] = min(minStepCost[(step-2) % 2] + cost[step-2], minStepCost[(step-1) % 2] + cost[step-1]); |
| 32 | + } |
| 33 | + return minStepCost[cost.size() % 2]; |
| 34 | +} |
| 35 | + |
| 36 | +// Fibonacci-like approach |
| 37 | +// Time Complexity: O(n) |
| 38 | +// Space Complexity: O(1) |
| 39 | +int minCostClimbingStairsFibonacci(vector<int>& cost) { |
| 40 | + if (cost.size() < 2) {return 0;} |
| 41 | + int twoStepBefore = cost[0]; |
| 42 | + int oneStepBefore = cost[1]; |
| 43 | + for (int step = 2; step < cost.size(); step++){ |
| 44 | + int current = cost[step] + min(oneStepBefore, twoStepBefore); |
| 45 | + twoStepBefore = oneStepBefore; |
| 46 | + oneStepBefore = current; |
| 47 | + } |
| 48 | + return min(oneStepBefore, twoStepBefore); |
| 49 | +} |
0 commit comments