LeetCode 746: Min Cost Climbing Stairs Solution
Master LeetCode problem 746 (Min Cost Climbing Stairs), a easy challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.
746. Min Cost Climbing Stairs
Problem Explanation
Explanation:
To solve this problem, we can use dynamic programming. We will create an array dp to store the minimum cost to reach each step. The base cases will be dp[0] = cost[0] and dp[1] = cost[1] as these are the costs to reach the first and second steps. For each subsequent step i, the minimum cost to reach that step will be cost[i] + min(dp[i-1], dp[i-2]). Finally, we return the minimum of the costs to reach the last two steps, which represents reaching the top of the floor.
Time Complexity:
The time complexity of this solution is O(n), where n is the number of steps.
Space Complexity:
The space complexity of this solution is O(n) to store the array dp.
:
Solution Code
class Solution {
public int minCostClimbingStairs(int[] cost) {
int n = cost.length;
int[] dp = new int[n];
dp[0] = cost[0];
dp[1] = cost[1];
for (int i = 2; i < n; i++) {
dp[i] = cost[i] + Math.min(dp[i-1], dp[i-2]);
}
return Math.min(dp[n-1], dp[n-2]);
}
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 746 (Min Cost Climbing Stairs)?
This page provides optimized solutions for LeetCode problem 746 (Min Cost Climbing Stairs) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.
What is the time complexity of LeetCode 746 (Min Cost Climbing Stairs)?
The time complexity for LeetCode 746 (Min Cost Climbing Stairs) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 746 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 746 in Java, C++, or Python.