Created
June 4, 2020 03:41
-
-
Save bhaveshmunot1/af53e29dbceebc350467afda1cea0838 to your computer and use it in GitHub Desktop.
Leetcode #746: Min Cost Climbing Stairs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Solution { | |
public: | |
int minCostClimbingStairs(vector<int>& cost) { | |
int n = cost.size(); | |
if (n == 0) { | |
return 0; | |
} | |
if (n == 1) { | |
return cost[0]; | |
} | |
vector<int> dp(n); | |
dp[0] = cost[0]; | |
dp[1] = cost[1]; | |
for (int i=2; i<n; i++) { | |
dp[i] = cost[i]+min(dp[i-1], dp[i-2]); | |
} | |
return min(dp[n-1], dp[n-2]); | |
} | |
}; | |
// Note: Space complexity of this solution can be reduced to O(1) by using 3-4 variables instead of an array/vector. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment