Skip to content

Commit 20cba96

Browse files
committed
Solved problem 746 : Min Cost Climbing Stairs
1 parent 417869e commit 20cba96

File tree

3 files changed

+53
-4
lines changed

3 files changed

+53
-4
lines changed

Dynamic Programming 1D/Easy/70_ClimbingStairs.cpp

+1-1
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22
* Problem: 70
33
* Name: Climbing Stairs
44
* Difficulty: Easy
5-
* Topic: Dynamic Programming (1D)
5+
* Topic: Dynamic Programming 1D
66
* Link: https://leetcode.com/problems/climbing-stairs/
77
*/
88

Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
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+
}

README.md

+3-3
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@
1616

1717
### Problems Solved
1818

19-
| Total | 45 |
19+
| Total | 46 |
2020
|:---:|:---:|
2121

2222
#### Search By Topic
@@ -28,7 +28,7 @@
2828
| Binary Search | 2 |
2929
| Binary Trees | 9 |
3030
| Bit Manipulation | 6 |
31-
| Dynamic Programming 1D | 1 |
31+
| Dynamic Programming 1D | 2 |
3232
| Dynamic Programming 2D | 0 |
3333
| Graphs | 1 |
3434
| Graphs Advanced | 0 |
@@ -46,7 +46,7 @@
4646

4747
| Difficulty | Number |
4848
|:---|---:|
49-
| Easy | 44 |
49+
| Easy | 45 |
5050
| Medium | 1 |
5151
| Hard | 0 |
5252

0 commit comments

Comments
 (0)