0/1 Knapsack
Dynamic programming for choices under a capacity limit
Take an item or leave it
Each item has a weight and a value, and each item may be chosen at most once. Define dp[i][w] as the greatest value possible using the first i items with capacity w. This state turns an exponential collection of subsets into a table of reusable subproblems.
Read the two source cells
If an item is too heavy, copy the value from the row above. Otherwise compare skipping it with taking it: dp[i-1][w] versus dp[i-1][w-weight] + value. The highlighted cells show both sources for every decision. The bottom-right result is 7, produced by items A and B.
| 0 | 1 | 2 | 3 | 4 | 5 | |
|---|---|---|---|---|---|---|
| ∅ | 0 | 0 | 0 | 0 | 0 | 0 |
| A | 0 | |||||
| B | 0 | |||||
| C | 0 | |||||
| D | 0 |
With no items or zero capacity, the best value is 0.
Complexity and variations
The table has n * W states, so time and full-table space are O(nW). Because each row only depends on the previous row, a one-dimensional implementation can reduce space to O(W) by iterating capacities backward.