Min Cost Climbing Stairs

25 min · minCostClimbingStairs()

The cheapest-looking first step can lead straight into an expensive staircase.

The array cost records what you pay when you step off each stair: leaving stair i costs cost[i]. You may begin on stair 0 or stair 1, then climb 1 or 2 stairs per move. Return the smallest total cost that gets you to the top, just past the final stair.

A few ground rules:

  • Starting on stair 0 or 1 costs nothing by itself; you pay when you leave that stair.
  • A final 1-step or 2-step move may land directly on the top.
  • Costs are never negative.

Constraints

  • 2 <= cost.length <= 1_000
  • 0 <= cost[i] <= 999

Hints

Price each arrival

Ask for the cheapest total that has paid for stair i. The previous move came from either i - 1 or i - 2.

The top has two entrances

You can reach the top by stepping off either of the final two stairs. Compute the cheapest paid total for both, then take the smaller one.

Two totals are enough

Each new total depends only on the previous two. Roll those values forward instead of storing a full array.

Follow-up

How would you return the actual sequence of stair indices on a cheapest route, not just its cost?

Visible cases

Examples

Example 1

ready
Input
cost = [
  10,
  15,
  20
]
Expected
15
Why
start at stair 1, pay 15, then jump to the top

Example 2

ready
Input
cost = [
  1,
  100,
  1,
  1,
  1,
  100,
  1,
  1,
  100,
  1
]
Expected
6
Why
small local costs combine into a six-cost route

Example 3

ready
Input
cost = [
  5,
  1
]
Expected
1
Why
start at stair 1 and leave it directly for the top

Interview signal

Asked at

AmazonGoogle
Loading editor

Console

ready to run

Ready to run.

3 cases are queued.

Run: visible + custom · Submit: full suite