746. Min Cost Climbing Stairs
Last updated
Last updated
/**
* Time complexity : O(N) where N is the length of cost.
* Space complexity : O(1), the space used by f1, f2.
*/
class Solution {
public int minCostClimbingStairs(int[] cost) {
int f1 = 0, f2 = 0;
for (int i = cost.length - 1; i >= 0; --i) {
int f0 = cost[i] + Math.min(f1, f2);
f2 = f1;
f1 = f0;
}
return Math.min(f1, f2);
}
}/**
* Time complexity : O(N) where N is the length of cost.
* Space complexity : O(1)
*/
class Solution {
public int minCostClimbingStairs(int[] cost) {
if(cost == null || cost.length == 0) {
return 0;
}
int n = cost.length;
if(n == 1) {
return cost[0];
}
for(int i = 2; i < cost.length; i++) {
cost[i] += Math.min(cost[i-2], cost[i-1]);
}
return Math.min(cost[n-2], cost[n-1]);
}
}