Created
June 8, 2021 06:25
-
-
Save vrat28/f428b383b9a1f266e8c4bdd3055fc61c to your computer and use it in GitHub Desktop.
Min Cost climbing stairs(DP | Bottom-up )
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(int[] cost) { | |
// The array's length should be 1 longer than the length of cost | |
// This is because we can treat the "top floor" as a step to reach | |
int minimumCost[] = new int[cost.length + 1]; | |
// Start iteration from step 2, since the minimum cost of reaching | |
// step 0 and step 1 is 0 | |
for (int i = 2; i < minimumCost.length; i++) { | |
int takeOneStep = minimumCost[i - 1] + cost[i - 1]; | |
int takeTwoSteps = minimumCost[i - 2] + cost[i - 2]; | |
minimumCost[i] = Math.min(takeOneStep, takeTwoSteps); | |
} | |
// The final element in minimumCost refers to the top floor | |
return minimumCost[minimumCost.length - 1]; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment