DSA/Lesson 11 of 11/6 min read
Dynamic Programming and Greedy
Optimal substructure, memoization vs tabulation, classic DP patterns like knapsack and LCS, and when greedy algorithms are correct.
On this page
Dynamic Programming
Dynamic programming (DP) solves a problem by breaking it into subproblems, solving each once, and storing the results. It applies when a problem has two properties.
Optimal Substructure
An optimal solution is built from optimal solutions of subproblems. Shortest paths have it: the shortest path from A to C via B contains the shortest path from A to B.
Overlapping Subproblems
The same subproblems are solved many times by naive recursion. Fibonacci: fib(n) needs fib(n-1) and fib(n-2), which share fib(n-3), and so on.
Memoization
Top-down: write the natural recursion, then cache results.
from functools import lru_cache
@lru_cache(maxsize=None)
def fib(n):
if n < 2:
return n
return fib(n - 1) + fib(n - 2)Easy to write and only computes states that are actually needed, but recursion depth can overflow the stack.
Tabulation
Bottom-up: fill a table in an order where dependencies are already computed.
def fib(n):
if n < 2:
return n
prev, cur = 0, 1
for _ in range(n - 1):
prev, cur = cur, prev + cur
return curNo recursion overhead, and often allows space optimization (keep only the last row or last two values).
| Memoization | Tabulation | |
|---|---|---|
| Direction | Top-down | Bottom-up |
| Implementation | Recursion + cache | Loops + table |
| States computed | Only needed ones | All |
| Stack overflow risk | Yes | No |
| Space optimization | Harder | Easy |
How to solve a DP problem
- Define the state: what does
dp[i](ordp[i][j]) mean, in words? - Write the recurrence: how does a state depend on smaller states?
- Base cases: smallest states with known answers.
- Order of computation: make sure dependencies are filled first.
- Answer: which state (or max over states) is the result?
- Optimize space if only recent rows are used.
Time complexity is usually number of states * work per state.
Classic DP patterns
1D DP
- Climbing stairs:
dp[i] = dp[i-1] + dp[i-2]. - House robber:
dp[i] = max(dp[i-1], dp[i-2] + nums[i]). - Coin change (min coins):
dp[a] = min(dp[a - c] + 1)over coinsc.O(amount * coins). - Word break:
dp[i]is true if somedp[j]is true ands[j:i]is in the dictionary.
0/1 Knapsack
Items with weight w[i] and value v[i], capacity W; each item taken at most once.
dp[i][c] = max(dp[i-1][c], # skip item i
dp[i-1][c - w[i]] + v[i]) # take item i, if it fitsO(n * W) time. Space-optimize to one array by iterating capacity backwards so each item is used once. Iterating forwards gives the unbounded knapsack (items reusable). Note this is pseudo-polynomial: W is a number, not an input size.
Variants: subset sum, partition equal subset sum, target sum.
Longest Common Subsequence
if a[i-1] == b[j-1]: dp[i][j] = dp[i-1][j-1] + 1
else: dp[i][j] = max(dp[i-1][j], dp[i][j-1])O(m * n). Used in diff tools and DNA alignment. A subsequence keeps order but need not be contiguous; a substring must be contiguous.
Longest Increasing Subsequence
O(n^2):dp[i] = 1 + max(dp[j])forjbeforeiwith smaller value.O(n log n): keeptails[k]= smallest tail of an increasing subsequence of lengthk + 1, and binary search where each new element goes.
Edit Distance
Minimum inserts, deletes and replacements to turn a into b (Levenshtein).
if a[i-1] == b[j-1]: dp[i][j] = dp[i-1][j-1]
else: dp[i][j] = 1 + min(dp[i-1][j], # delete
dp[i][j-1], # insert
dp[i-1][j-1]) # replaceOther families
| Family | Examples |
|---|---|
| Grid DP | Unique paths, minimum path sum |
| Interval DP | Matrix chain multiplication, burst balloons |
| DP on trees | House robber III, tree diameter |
| Bitmask DP | Travelling salesman O(2^n * n^2) |
| State machine DP | Stock buy and sell with cooldown |
Greedy Algorithm
A greedy algorithm makes the locally best choice at each step and never reconsiders. It is usually simpler and faster than DP, but only correct for some problems.
Greedy Choice Property
A globally optimal solution can be reached by making a locally optimal choice first. Together with optimal substructure, this makes greedy correct. Prove it with an exchange argument: show any optimal solution can be transformed to include the greedy choice without getting worse.
When greedy fails
Coin change with coins [1, 3, 4] and amount 6: greedy takes 4 + 1 + 1 (3 coins), but 3 + 3 uses 2. Use DP. Greedy works for canonical coin systems like [1, 5, 10, 25].
Similarly, fractional knapsack is greedy (sort by value per weight), but 0/1 knapsack needs DP.
Activity Selection
Choose the maximum number of non-overlapping intervals: sort by end time, and repeatedly pick the next activity that starts after the last chosen one ends. O(n log n).
Related interval problems:
| Problem | Greedy rule |
|---|---|
| Non-overlapping intervals (min removals) | Sort by end, count overlaps |
| Merge intervals | Sort by start, merge if overlapping |
| Meeting rooms II | Sort starts and ends, or min-heap of end times |
| Minimum arrows to burst balloons | Sort by end |
Huffman Coding
Optimal prefix-free code for data compression. Repeatedly merge the two lowest-frequency nodes (min-heap) into a new node until one tree remains. Frequent characters get shorter codes. O(n log n).
Other greedy classics: jump game, gas station, task scheduler, Dijkstra, Prim and Kruskal.
DP vs greedy vs divide and conquer
| Greedy | DP | Divide and conquer | |
|---|---|---|---|
| Choices | One local choice | Try all, keep best | Split |
| Subproblems | One remains | Overlapping | Independent |
| Correctness | Needs proof | Always (if state is right) | Always |
| Speed | Fastest | Slower | Varies |
Quick revision
- DP needs optimal substructure and overlapping subproblems.
- Memoization is top-down recursion plus cache; tabulation is bottom-up loops.
- Define the state in words first, then the recurrence, base cases and order.
- 0/1 knapsack: iterate capacity backwards in 1D; forwards gives unbounded.
- LCS and edit distance are
O(m * n)grid DPs; LIS can beO(n log n). - Greedy needs the greedy choice property; prove with an exchange argument.
- Coin change with arbitrary coins and 0/1 knapsack break greedy; use DP.
- Interval scheduling: sort by end time.