File tree Expand file tree Collapse file tree 1 file changed +29
-0
lines changed
24 - Dynamic Programming Problems/02 - Min Cost Climbing Stairs Expand file tree Collapse file tree 1 file changed +29
-0
lines changed Original file line number Diff line number Diff line change 1+ class Solution {
2+ public:
3+ // Function to calculate the minimum cost to climb the stairs using optimized tabulation
4+ int solve (vector<int >& cost, int n) {
5+ // Step 1: Initialize two variables to store the minimum cost for the previous two steps
6+ int i_1 = cost[1 ]; // Represents the cost to reach the first step (index 1)
7+ int i_2 = cost[0 ]; // Represents the cost to reach the second step (index 0)
8+
9+ // Step 2: Iterate through the cost array starting from the third step (index 2)
10+ for (int i = 2 ; i < n; i++) {
11+ // The minimum cost to reach the current step is the cost at this step plus the minimum
12+ // of the costs from the two previous steps (i-1 and i-2)
13+ int curr = cost[i] + min (i_1, i_2);
14+
15+ // Update the variables for the next iteration
16+ i_2 = i_1; // Move the previous step to i_2
17+ i_1 = curr; // Set the current minimum cost as i_1
18+ }
19+
20+ // Step 3: The minimum cost to reach the top is the minimum of the last two steps
21+ return min (i_1, i_2);
22+ }
23+
24+ // Main function to calculate the minimum cost to climb to the top of the stairs
25+ int minCostClimbingStairs (vector<int >& cost) {
26+ // Call the `solve` function with the cost array and its size
27+ return solve (cost, cost.size ());
28+ }
29+ };
You can’t perform that action at this time.
0 commit comments