#746

Min Cost Climbing Stairs

Easy 1D DP

  1. Read
  2. Understand
  3. Hints
  4. Approach
  5. Solution
  6. Solved

?The problem

cost[i] is paid when you step on stair i, and you can then climb 1 or 2 stairs. You may start on stair 0 or 1. Return the minimum cost to get past the last stair.

This is a short summary in our own words. Read the full statement and examples on LeetCode: open problem ↗

◎Understanding

Really asking: cheapest way to get past the top when each step has a cost.

Why this works: dp[i] = min(dp[i-1] + cost[i-1], dp[i-2] + cost[i-2]).

Example: cost [10, 15, 20]

dp[2] = min(0+15, 0+10) = 10dp[3] = min(10+20, 0+15) = 15

✦Hints open one at a time

↗Approach

</>Solution (Java)

!Common mistake

Returning dp[n − 1] — the top is past the last stair, index n.

Solve on LeetCode ↗
Complexity
  • Time: O(n).
  • Space: O(1).
Topic: Dynamic Programming
🎬 Episodes 86–96: video coming soon