Typorithm · easy

Min Cost Climbing Stairs

▷ Interactive algorithm labmin-cost-climbing-stairs-dpdynamic-programmingminimizationspace-optimized
Saved on this device
Full lesson · 8 learning steps Open any exercise for focused practice
1

Step 1 of 8 · intro card

Learn Min Cost Climbing Stairs

0%

Dynamic Programming

Min Cost Climbing Stairs chooses the cheaper of reaching the top from one step below or two steps below.

The top is one position after the last cost.

Each state is the minimum cost to reach a position.

The transition compares paying from one step below versus two steps below.

Preparing algorithm lab…
01

State: min cost to reach position i.

02

Base: cost before first two positions is 0.

03

Transition: min(one-step, two-step).

04

Time O(n), space O(1).

function minCostClimbingStairs(cost) {
  let twoStepsBefore = 0;
  let oneStepBefore = 0;

  for (let i = 2; i <= cost.length; i++) {
    const takeOne = oneStepBefore + cost[i - 1];
    const takeTwo = twoStepsBefore + cost[i - 2];
    const current = Math.min(takeOne, takeTwo);
    twoStepsBefore = oneStepBefore;
    oneStepBefore = current;
  }

  return oneStepBefore;
}

Read the implementation

Connect each part of the code to the concept before you type.

1. Free start

You can start before step 0 or 1 with no paid cost.

let twoStepsBefore = 0

2. One-step option

Pay the cost of the stair one step below.

const takeOne = oneStepBefore + cost[i - 1]

3. Two-step option

Pay the cost of the stair two steps below.

const takeTwo = twoStepsBefore + cost[i - 2]

4. Min transition

Choose the cheaper way to reach this position.

const current = Math.min(takeOne, takeTwo)

A complete learning loop

01

Understand

Read the concept map and follow the code breakdown.

02

Reconstruct

Type the implementation, repair mistakes and work through every recall exercise.

03

Verify

Use the final check without hints; revisit weak concepts in short practice sessions.

Min Cost Climbing Stairs: Visual Walkthrough & Practice · Typorithm | ApplyDjinn