1-D DP
Keep a notebook with one line per day. Each line holds the best total so far, so tomorrow’s line only needs to look at the last two. The final line is the answer, built without ever redoing a day.
2 · Watch
1-D DP in 60 seconds
3 · Now you drive
House Robber
4 · Your turn
Start from this
// dp[i] is the answer for the first i items.
const dp = new Array(n + 1).fill(0);
// The smallest case, known without any work.
dp[0] = base;
for (let i = 1; i <= n; i++) {
// Build from answers you already have.
dp[i] = best(dp[i - 1], fromEarlier(dp, i));
}
return dp[n];Easy ways to go wrong
- Not saying out loud what dp[i] means before coding.
- Getting the base case wrong, which poisons every later cell.
- Filling the table in an order where a cell’s inputs aren’t ready yet.
- Easy01
Climbing Stairs
Warm-up: each step adds the two ways below it.
Ways to reach a stair: the ways to the two below it, added.
- Time
- O(n)
- Space
- O(1)
- Medium02
House Robber
The one you just watched. Write it from memory, then keep only the last two cells for O(1) space.
At each spot: take it plus the best from two back, or skip it.
- Time
- O(n)
- Space
- O(1)
- Medium03
House Robber II
Same street, but the ends are neighbours too.
Solve the row twice: once without the first item, once without the last.
- Time
- O(n)
- Space
- O(1)
- Medium04
Longest Palindromic Substring
Grow the answer out from each centre.
Expand from every centre: a long palindrome holds a shorter one.
- Time
- O(n²)
- Space
- O(1)
Also works with Two Pointers.
- Medium05
Palindromic Substrings
Count the palindromes around every centre.
Every centre grows its own set of palindromes.
- Time
- O(n²)
- Space
- O(1)
Also works with Two Pointers.
- Medium06
Decode Ways
Each digit stands alone or pairs with its neighbour.
Each position builds on the one-digit and two-digit reads before it.
- Time
- O(n)
- Space
- O(1)
- Medium07
Coin Change
Fewest coins for each amount, built up amount by amount.
The best for an amount is one coin plus the best for what’s left.
- Time
- O(a·c)
- Space
- O(a)
- Medium08
Maximum Product Subarray
Track the best and worst ending at each step.
A negative swaps best and worst, so track both.
- Time
- O(n)
- Space
- O(1)
- Medium09
Word Break
Each cut asks whether the prefix already breaks.
A cut works if the part before it already breaks and the part after it is a word.
- Time
- O(n³)
- Space
- O(n)
Also works with Backtracking.
- Medium10
Longest Increasing Subsequence
Each number extends the best run before it.
Each value extends the best chain ending at a smaller value. That is O(n²); keeping the smallest tail for each length, found by binary search, gets it to O(n log n).
- Time
- O(n log n)
- Space
- O(n)
Also works with Binary Search.