DSA AnimatorDSA animations
Min Cost Climbing Stairs LC #746 Easy DP
Problem

Cost array for each step. You can start at step 0 or 1. Pay cost[i] to climb from step i (then climb 1 or 2 steps). Return minimum cost to reach the top.

Example
[10,15,20] → 15 (start at index 1, pay 15, climb 2 to top)
Constraints: 2 ≤ cost.length ≤ 1000
Try Examples
Custom:
Approach
dp[i] = min cost to reach top from step i
dp[i] = cost[i] + min(dp[i-1], dp[i-2]). Answer = min(dp[n-1], dp[n-2]).
Cost Array & DP
Load an example.
Variables
i
—
a (dp[i-2])
—
b (dp[i-1])
—
min cost
—
Step Logic
Press ▶ Play or Next Step to begin.
💵
Ready
0 / 0
Select an example and press Play.
Algorithm
1
a=cost[0], b=cost[1] (base)
2
For i=2..n-1: c = cost[i] + min(a,b); a=b; b=c
3
Return min(a, b)
Time
O(n)
Space
O(1)
Why This Works

dp[i] = min cost to reach top from step i. You can jump 1 or 2 steps. Answer is min(dp[n-1], dp[n-2]) since you can finish from either of the last two steps.

How to solve Min Cost Climbing Stairs

LeetCode 746 · Easy · Dynamic Programming · Pattern: 1D DP

Why the obvious approach is slow

Trying every combination of single and double steps is exponential. Many of those paths share the same suffix, which we keep recomputing.

The key idea

Let dp of i be the cheapest cost to arrive at position i. Starting is free, so dp of 0 and dp of 1 are both 0. To arrive at i, you either stood on i −1 and paid its cost, or stood on i minus 2 and paid its cost. So dp of i is the smaller of dp of i −1 plus cost of i −1, and dp of i minus 2 plus cost of i minus 2. The top is position n, so the answer is dp of n.

Remember

Define the state precisely, here the cost to arrive at i. The top is one past the last step.

Run the animation above on your own input, or watch the 2:05 video explanation of Min Cost Climbing Stairs with a dry run and Java code.

More Dynamic Programming problems