1. Free start
You can start before step 0 or 1 with no paid cost.
let twoStepsBefore = 0Typorithm · easy
Step 1 of 8 · intro card
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.
State: min cost to reach position i.
Base: cost before first two positions is 0.
Transition: min(one-step, two-step).
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;
}Connect each part of the code to the concept before you type.
You can start before step 0 or 1 with no paid cost.
let twoStepsBefore = 0Pay the cost of the stair one step below.
const takeOne = oneStepBefore + cost[i - 1]Pay the cost of the stair two steps below.
const takeTwo = twoStepsBefore + cost[i - 2]Choose the cheaper way to reach this position.
const current = Math.min(takeOne, takeTwo)Read the concept map and follow the code breakdown.
Type the implementation, repair mistakes and work through every recall exercise.
Use the final check without hints; revisit weak concepts in short practice sessions.
Algorithm lab · interactive
InputCosts [10,15,20,5,8,7]
Follow temporary values, local state and supporting structures at this step.
↗ The 7-cell working table above is itself auxiliary memory. Input values are shown separately.
Input · not auxiliary memory
Input6 entries
Around this step
Small, reproducible examples · ← → step · Space play/pause · Home/End first/last state