Skip to content

Commit 3dc7ccf

Browse files
authored
Create 03 - Bottom-Up | DP | Approach.cpp
1 parent a337a8e commit 3dc7ccf

File tree

1 file changed

+30
-0
lines changed

1 file changed

+30
-0
lines changed
Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
class Solution {
2+
public:
3+
// Function to calculate the minimum cost to climb the stairs using tabulation
4+
int solve(vector<int>& cost, int n) {
5+
// Step 1: Create a DP table `dp` of size `n+1` to store the minimum cost at each step
6+
vector<int> dp(n + 1);
7+
8+
// Step 2: Initialize the base cases
9+
// If starting at the first step, the cost is simply `cost[0]`
10+
dp[0] = cost[0];
11+
// If starting at the second step, the cost is simply `cost[1]`
12+
dp[1] = cost[1];
13+
14+
// Step 3: Fill the DP table for steps from 2 to n-1
15+
for (int i = 2; i < n; i++) {
16+
// The minimum cost to reach step `i` is the cost at step `i` plus
17+
// the minimum cost to reach either of the two previous steps
18+
dp[i] = cost[i] + min(dp[i - 1], dp[i - 2]);
19+
}
20+
21+
// Step 4: The minimum cost to reach the top is the minimum of the last two steps
22+
return min(dp[n - 1], dp[n - 2]);
23+
}
24+
25+
// Main function to calculate the minimum cost to climb to the top of the stairs
26+
int minCostClimbingStairs(vector<int>& cost) {
27+
// Call the `solve` function with the cost array and its size
28+
return solve(cost, cost.size());
29+
}
30+
};

0 commit comments

Comments
 (0)