Skip to main content

746 - Min Cost Climbing Stairs

Difficulty: Easy | Pattern: Dynamic Programming | Company tags: Amazon, Google, Adobe

Problem Statement

You are given an integer array cost where cost[i] is the cost of i-th step on a staircase. Once you pay the cost, you can either climb one or two steps.

You can either start from the step with index 0, or the step with index 1.

Return the minimum cost to reach the top of the floor (beyond the last step).

Example 1:

Input: cost = [10,15,20]
Output: 15
Explanation: Start at index 1, pay 15, climb 2 steps → top.

Example 2:

Input: cost = [1,100,1,1,1,100,1,1,100,1]
Output: 6

Algorithm Flow

Approach: DP — O(n), O(1) space

Key insight: dp[i] = minimum cost to leave step i. To leave step i, you had to come from i-1 or i-2:

dp[i] = cost[i] + min(dp[i-1], dp[i-2])

The answer is min(dp[n-1], dp[n-2]) — reach top from the last or second-to-last step.

def minCostClimbingStairs(cost: list[int]) -> int:
n = len(cost)
if n == 2:
return min(cost)

prev2, prev1 = cost[0], cost[1]

for i in range(2, n):
curr = cost[i] + min(prev1, prev2)
prev2, prev1 = prev1, curr

return min(prev1, prev2)

Dry Run

cost = [10,15,20]

icost[i]prev2prev1curr
init1015
22020+min(15,10)=25

After: prev2=15, prev1=25

Return min(15, 25) = 15

cost = [1,100,1,1,1,100,1,1,100,1] → answer = 6 (skip all high steps)

Edge Cases

  • Two steps → min(cost) (take whichever single step is cheaper)
  • All same cost → always take 2 steps (skip every other)

Complexity

  • Time: O(n)
  • Space: O(1)