πDay 9. Min Cost Climbing Stairs π§
The problem can be found at the following link: Question Link
π‘ Problem Description:
Given an array of integers cost[], where cost[i] represents the cost of the i-th step on a staircase, you can either:
Pay the cost at
i-thstep and move one step forward.Pay the cost at
i-thstep and move two steps forward.
Return the minimum cost required to reach the top of the floor.
π Assumptions:
0-based indexing
You can start either from step 0 or step 1
π Example Walkthrough:
Example 1:
Input:
cost[] = [10, 15, 20]Output:
15Explanation:
The cheapest way is:
Start at
cost[1] = 15Jump 2 steps to the top (no cost at the top)
Example 2:
Input:
cost[] = [1, 100, 1, 1, 1, 100, 1, 1, 100, 1]Output:
6Explanation:
The cheapest way is:
1 β 3 β 4 β 6 β 7 β 9 (Total cost = 1 + 1 + 1 + 1 + 1 + 1 = 6)
Constraints:
$(2 \leq \text{cost.length} \leq 1000)$
$2 β€ cost.size() β€ 10^5$
$(0 \leq \text{cost[i]} \leq 999)$
π― My Approach:
Algorithm Steps:
Use two variables
aandbto keep track of the minimum cost of the last two steps.Iterate through the cost array, updating
busing the recurrence relation:b = cost[i] + min(a, b)a = previous b(before update)
Return
min(a, b), representing the minimum cost to reach the top.
π Time and Auxiliary Space Complexity
Expected Time Complexity:
O(N), as we iterate through thecostarray once.Expected Auxiliary Space Complexity:
O(1), as we use only a constant amount of extra space (aandb).
π Solution Code
Code (C++)
class Solution {
public:
int minCostClimbingStairs(vector<int>& cost) {
int a = cost[0], b = cost[1];
for (int i = 2; i < cost.size(); i++)
tie(a, b) = make_tuple(b, cost[i] + min(a, b));
return min(a, b);
}
};Code (Java)
class Solution {
public int minCostClimbingStairs(int[] cost) {
int a = cost[0], b = cost[1];
for (int i = 2; i < cost.length; i++) {
int temp = b;
b = cost[i] + Math.min(a, b);
a = temp;
}
return Math.min(a, b);
}
}Code (Python)
class Solution:
def minCostClimbingStairs(self, cost):
for i in range(2, len(cost)):
cost[i] += min(cost[i - 1], cost[i - 2])
return min(cost[-1], cost[-2])π― Contribution and Support:
For discussions, questions, or doubts related to this solution, feel free to connect on LinkedIn: Any Questions. Letβs make this learning journey more collaborative!
β If you find this helpful, please give this repository a star! β
πVisitor Count
Last updated