0/1 Knapsack
dp[i][w] = max(dp[i-1][w], dp[i-1][w - wt] + val); each item is taken at most once.
Decision · step 3 of 34Knapsack: 0/1 knapsack, capacity 7
Item 1 (weight 1, value 1) at capacity 1. Skip: 0 from above. Take: 1 + 0 from the previous row at capacity 0 = 1. Best: 1, take.
What you will see
Row per item, column per capacity; each cell reads the cell above and the cell above-left by the item's weight.
Cost
| Best | O(n * W) |
|---|---|
| Average | O(n * W) |
| Worst | O(n * W) |
| Space | O(W) |
Pseudo-polynomial in W; O(W) space with a single row iterated right to left.
How you work with it here
play it through, step one change at a time, scrub to any step, run it on your own input, predict what happens next.
Screen readers: Table cells announce their state and value; each step announces which cells were read and the value written.
Reduced motion: Dependency arrows appear statically and the cell value crossfades.