Min Cost Climbing Stairs

EasyDynamic Programming · 1-D DP🧩 1-D Dynamic ProgrammingLeetCode #746 ↗Updated

Problem

A staircase has steps 0..n-1, and stepping off step i costs cost[i]. After paying, you may climb one or two steps. You may start on step 0 or step 1 for free. Return the minimum total cost to reach the top, which is the position just past the last step (index n).
Inputcost = [10,15,20]Output15
Inputcost = [1,100,1,1,1,100,1,1,100,1]Output6

2 ≤ n ≤ 1000  ·  0 ≤ cost[i] ≤ 999

Try it yourself

Java
class Solution {
    public int minCostClimbingStairs(int[] cost) {
        
    }
}
Your code is saved in this browser.Submit on LeetCode ↗
Key insight
Let reach(i) be the cheapest way to stand on position i. You arrive from i-1 or i-2, paying that step's cost: reach(i) = min(reach(i-1)+cost[i-1], reach(i-2)+cost[i-2]). Only the last two values matter.
Pattern1-D Dynamic Programming

Instinct The best answer at position i depends only on a few earlier positions (i-1, i-2, ...) - write dp[i] from its predecessors, then roll it into variables.

Memory hack Look back, pick best, roll forward - every step only remembers the last couple of stairs it stood on.

Open the 1-D Dynamic Programming guide →

Approaches

Brute ForcePlain Recursion

Time O(2n)Space O(n)

Translate the recurrence directly: to reach position i, try both possible previous positions and keep the cheaper total. Positions 0 and 1 are free starting points. The same sub-positions are recomputed over and over, so the call tree doubles at every level.

Java
public int minCostClimbingStairs(int[] cost) {
    return reach(cost, cost.length);
}

// cheapest cost to stand on position i (n = the top)
private int reach(int[] cost, int i) {
    if (i <= 1) return 0; // free starting steps
    int fromOne = reach(cost, i - 1) + cost[i - 1];
    int fromTwo = reach(cost, i - 2) + cost[i - 2];
    return Math.min(fromOne, fromTwo);
}

Correct and obvious, but exponential — times out long before n = 1000.

At a glance

LevelApproachTimeSpace
Brute ForcePlain RecursionO(2n)O(n)
BetterMemoized Recursion (Top-Down)O(n)O(n)
OptimalBottom-Up with Two VariablesO(n)O(1)
Common pitfalls
  • Returning reach(n-1) — the top is past the last step, index n.
  • Charging a cost for the starting step — steps 0 and 1 are reached for free.
  • Adding cost[i] on arrival instead of the cost of the step you leave from.
Interview tips
  • Define the state in words first: “cheapest cost to stand on position i”.
  • Show the exponential recursion, point out repeated subproblems, then add the memo.
  • Finish by noting only two previous values are read, so space drops to O(1).
Pattern
1-D DP over positions → each state depends on a fixed number of earlier states (Fibonacci-style).
My notes saved in this browser