0/1 knapsack
medium 22 minPack items with weights and values into a bag of capacity W to get the most value, each item taken whole or not at all.
Remember it
The few things worth knowing cold, and how to make them stick.
Memory hook
Take it or leave it, look one row up, keep the max.
Packing a suitcase with a weight limit. Shirt 2 kg worth 10, camera 3 kg worth 50, laptop 6 kg worth 100, limit 5 kg: the laptop does not fit, so shirt and camera for 60. For each item you ask one question: is my best packing with it better than my best packing without it?
Cheat sheet
- State
- dp[i][w] = best value, first i items, room w
- Leave
- dp[i-1][w]
- Take
- v_i + dp[i-1][w - w_i], only if it fits
- Base
- row 0 and column 0 are zeros
- Time
- O(n·W), pseudo-polynomial
- Space
- O(n·W) table, O(W) one row
- 1D loop
- w from W down to w_i
- Walk back
- changed: packed, subtract weight; equal: left
- Example
- capacity 7 camping trip gives 9 (bag + tent)
Spot it when you see
- Choose a subset under a budget (weight, cost, time) to maximise a total.
- Each item can be used at most once.
- Can some numbers sum exactly to a target, or split into equal halves?
- Count the ways to reach a total with each number used once, or with + and - signs.
- The capacity is a moderate integer (up to about 10^4 or 10^5).
Tricks that stick
- TLC: Take = v_i + dp[i-1][w - w_i], Leave = dp[i-1][w], Choose the max.
- Look up for leave, look up and left by the weight for take.
- 0/1 sweeps backward, unbounded sweeps forward.
- Subset sum family: same loop, swap max for or (can we?) or += (how many?).
- Target sum: P = (S + T) / 2.
Do not forget
- Sweeping the 1D loop left to right, which turns it into unbounded knapsack.
- Reading dp[i][w - w_i] instead of dp[i-1][w - w_i] in the 2D take option.
- Missing the fit check: a negative index silently reads the end of the row in Python.
- Trusting greedy by value per weight.
- Memo keyed on the item index only.
- Building a table when W is huge: check the numbers first.