Min Cost Climbing Stairs

Easy

Topics
ArrayDynamic Programming

Given an array cost where cost[i] is the cost of step i, you can climb 1 or 2 steps and start from index 0 or 1. Return the minimum cost to reach the top (just past the last step).

Example 1

100151202
steps paid for
Each cell is the toll for standing on that step, and from a step you may climb one or two. You may start on either of the first two steps, and the top is above the last one — so the final step does not have to be paid for. The shaded steps cost 15 in total.
Cells are the array values; the small numbers underneath are indices.
Input:  cost = [10,15,20]
Output: 15

Example 2

10100112131410051617100819
steps paid for
Input:  cost = [1,100,1,1,1,100,1,1,100,1]
Output: 6

Constraints

  • 2 <= cost.length <= 1000
  • 0 <= cost[i] <= 999
Editorial — intuition, approach, complexity and pitfalls

Intuition

The cost to stand on a step is its own cost plus the cheaper of the two ways to get there (one or two steps below). Build these minimum costs upward; the top is just past the last step.

Approach

  1. Track the min cost to reach the previous two steps.
  2. For each step: cost_here = step + min(prev, prevPrev).
  3. Return min(last, secondLast) since you can step onto the top from either.

Walkthrough

cost = [10, 15, 20]
reach step0=10, step1=15, step2=20+min(10,15)=30
top = min(step1, step2) = min(15, 30) = 15

Complexity

  • Time — O(n): one pass.
  • Space — O(1): two rolling variables.

Common Pitfalls

  • Return b, not a. After the loop b is the cost of standing past the last step and a is one step short of it, so returning a gives 10 instead of 15 on the first example.
  • You may start at index 0 or index 1, which is why both a and b begin at 0 rather than at nums[0].

Full Solution — all languages

class Solution:
    def minCostClimbingStairs(self, nums):
        a = b = 0
        for i in range(2, len(nums) + 1):
            a, b = b, min(b + nums[i - 1], a + nums[i - 2])
        return b
SensAI
Beta
Tap the mic to stop voice mode