Work backward while retaining only the optimal costs from the next two positions, then choose the cheaper starting step.
Complexity
O(n) time and O(1) extra space.
Find the minimum cost needed to move beyond the top of a staircase when each move climbs one or two steps.
Work backward while retaining only the optimal costs from the next two positions, then choose the cheaper starting step.
O(n) time and O(1) extra space.
package main
func minCostClimbingStairs(cost []int) int {
oneAhead, twoAhead := 0, 0
for index := len(cost) - 1; index >= 0; index-- {
current := cost[index] + minCost(oneAhead, twoAhead)
twoAhead, oneAhead = oneAhead, current
}
return minCost(oneAhead, twoAhead)
}
func minCost(a int, b int) int {
if a < b {
return a
}
return b
}
class Solution:
def minCostClimbingStairs(self, cost: list[int]) -> int:
one_ahead = two_ahead = 0
for value in reversed(cost):
current = value + min(one_ahead, two_ahead)
two_ahead, one_ahead = one_ahead, current
return min(one_ahead, two_ahead)
function minCostClimbingStairs(cost: number[]): number {
let oneAhead = 0;
let twoAhead = 0;
for (let index = cost.length - 1; index >= 0; index -= 1) {
const current = cost[index] + Math.min(oneAhead, twoAhead);
twoAhead = oneAhead; oneAhead = current;
}
return Math.min(oneAhead, twoAhead);
}