SDE & MLE Prep

746. Min Cost Climbing Stairs

Problem

cost[i] is what you pay when you leave step i, after which you climb 1 or 2 steps. You may start on step 0 or step 1. Return the minimum cost to get past the last step.

Example: [10,15,20] → 15; [1,100,1,1,1,100,1,1,100,1] → 6

dp[i] = min cost to stand on step i = min(dp[i−1] + cost[i−1], dp[i−2] + cost[i−2]); answer dp[n].

Complexity: O(n) time, O(1) space.

class Solution:
    def minCostClimbingStairs(self, cost: List[int]) -> int:
        a = b = 0            # dp[i-2], dp[i-1]
        for i in range(2, len(cost) + 1):
            a, b = b, min(b + cost[i - 1], a + cost[i - 2])
        return b