Skip to content

DP — Min Cost Climbing Stairs ​

↗ LeetCode: Min Cost Climbing Stairs · Easy · pattern chapter →

Asked atAmazonMetaGoogle

Each step has cost. Start at 0 or 1; step 1 or 2. Min cost to reach past-the-end.

Example 1 — cost=[10,15,20] → 15 (start at 1, one step past → cost 15) Example 2 — cost=[1,100,1,1,1,100,1,1,100,1] → 6 (skip the 100s) Example 3 — cost=[0,0,0,0] → 0 (all free)

Constraints — 2 ≤ n ≤ 1000. Brute recursion tries +1 or +2 at each step — O(2ⁿ) ≈ 10³⁰¹ ops at n=1000 (10¹ magnitude → dead universes over). Rolling DP is O(n) = 10⁶ pointer ops at hot-path scale = <1 ms.

Progressive Hints
Try to solve it yourself first. Reveal hints only when stuck — each hint is progressively more specific.
---
⏱️Interview timer00:00
Practice under interview pressure. Start when you begin reading; stop when you finish. Save best only when you had a full working solution.
Target for interview: Medium = 20-25 min · Hard = 30-40 min · Best time persists on this device only.

Approach 1 — Brute recursion (no memo) ​

Intuition. Recurse from each starting step; at each step, try +1 or +2. Return min.

Complexity — Time O(2ⁿ); Space O(n) stack. TLE past n=30. In an interview say "same subproblems retread — memoize on step index → O(n)."


Approach 2 — DP O(1) space (canonical) ​

Insight. dp[i] = min(dp[i-1] + cost[i-1], dp[i-2] + cost[i-2]). Only need last two → constant space.

java
int minCostClimbingStairs(int[] cost) {
    int a = 0, b = 0;
    for (int i = 2; i <= cost.length; i++) {
        int c = Math.min(b + cost[i-1], a + cost[i-2]);
        a = b; b = c;
    }
    return b;
}
Execution Trace
DP O(1) space (canonical)
i100151202phase = start
Step 1 / 3Initialize scan.

Complexity — Time O(n); Space O(1). Say aloud in an interview: "same rolling-DP as Climbing Stairs and Fibonacci — 2-element rolling window."


Try it yourself ​

Complexity summary ​

ApproachTimeSpaceGrade
Brute recursionO(2ⁿ)O(n)TLE past n=30
Rolling DPO(n)O(1)Canonical

When to use which ​

  • Standard → rolling DP.
  • Return steps taken → track predecessors.
  • k-step variants → same skeleton with min over last k.
✨AI Study CompanionBeta
Was this page helpful?

Released under MIT license.

💡 Quick shortcuts
H HintsR Run JavaA AI Help