๐งฎ Module 5
๐๏ธ DP State Design
The most important DP skill: what to put in dp[]. Derive state from first principles.
๐๏ธ The Most Important DP Skill
Beginners struggle with DP not because the math is hard, but because they don't know what to put in dp[]. This module teaches you to derive the state definition from first principles โ every time.
The 3 Questions to Find Your State
What changes between recursive calls?
The parameters that change = your state dimensions.
House Robber: only
LCS: both
Stocks with k transactions:
House Robber: only
i (current index) changes โ 1D state dp[i]
LCS: both
i and j (positions in two strings) change โ 2D state dp[i][j]
Stocks with k transactions:
day, k, holding โ 3D state dp[day][k][holding]What affects future decisions?
Only include in state what is necessary to make the optimal decision going forward.
Knapsack: need
House Robber: do NOT need "how I got here" โ only current index matters.
Stock cooldown: need
Knapsack: need
remaining_capacity because it limits future choices.
House Robber: do NOT need "how I got here" โ only current index matters.
Stock cooldown: need
holding flag because you can't buy if you already hold.What does dp[state] represent?
Write it in English. This IS your recurrence.
dp[i] = max money robbing from house i to end
dp[i][w] = max value using first i items with capacity w
dp[i][j] = LCS length of s1[0..i] and s2[0..j]State Dimension Reference
| State | When to use | Examples | Space |
|---|---|---|---|
dp[i] | Single sequence, one changing param | Fibonacci, House Robber, LIS | O(n) |
dp[i][j] | Two sequences OR index + constraint | LCS, Edit Distance, Knapsack | O(nยฒ) |
dp[i][j][k] | Three constraints (often reducible) | Stocks with k txns, 3D Grid | O(nยณ) |
dp[row][col] | 2D grid movement | Unique Paths, Min Path Sum | O(mยทn) |
dp[day][hold] | State machine at each step | Stock Buy/Sell with cooldown | O(n) |
dp[mask] | Subset of items visited (nโค20) | TSP, Bitmask DP | O(2โฟ) |
dp[i][j] interval | Subarray/substring of length j-i | MCM, Burst Balloons | O(nยฒ) |
dp[node] | Tree โ depends on subtree results | House Robber III, Diameter | O(n) |
Worked Examples โ Deriving State from Scratch
State Reduction โ From 3D to 1D
๐ก Always try to reduce dimensions
If dp[i] only depends on dp[i-1] โ use two variables. If dp[i][j] only depends on row i-1 โ use 1D rolling array. This is what separates good solutions from great ones.
| Original | Reduced | Trick |
|---|---|---|
dp[n] Fibonacci | a, b โ O(1) | Only need prev 2 values |
dp[n][W] Knapsack | dp[W] โ O(W) | Iterate weights in reverse |
dp[m][n] LCS | dp[n] with prev var โ O(n) | Row i only needs row i-1; save diagonal in prev |
dp[n][k][2] Stocks | buy, sell arrays โ O(k) | At each day only 2 states per transaction count |