0/1 knapsack
Knapsack asks you to pick items with the highest total value while staying under a capacity.
How it works
Picture a row with one cell for each capacity. For a weight-2, value-4 item, the candidate at capacity 4 is the previous value at capacity 2 plus 4. Reading a previous-row result matters: that number must describe a choice made before the current item could be used.
Walk through an example
For each item and capacity, compare skipping the item with taking it once. The take option adds its value to the best answer for the remaining capacity using earlier items.
What to watch for
If you compress the table to one row, scan capacities downward for 0/1 knapsack. Scanning upward could let a single item contribute twice.
Code example
def knapsack(items, capacity):
best = [0] * (capacity + 1)
for weight, value in items:
for c in range(capacity, weight - 1, -1):
best[c] = max(best[c], best[c - weight] + value)
return best[capacity]Check your understanding
What is the highest value?
See the example and explanation
- Worked example
- Given
Capacity 4. Items have (weight, value) (3,5), (2,4), and (2,3). - Answer
7
The two weight-2 items fit together and have value 4 + 3. The weight-3 item cannot combine with either one.