TExcelTAD
Home › Data Structures & Algorithms › The 0/1 Knapsack Problem

The 0/1 Knapsack Problem

You are packing a backpack that can carry at most W kilograms. Each item has a weight and a value. Which items should you take to maximise the total value without exceeding the weight limit? "0/1" means each item is either taken whole (1) or left behind (0): no splitting, no duplicates.

The same problem appears when choosing projects within a budget, loading cargo, or selecting ads for a limited time slot.

Our example

Capacity W = 10 kg:

Item Weight (kg) Value
tent 6 66
stove 5 50
camera 5 54
book 2 18

Brute force

With n items there are 2ⁿ subsets. For 4 items that's 16, so we can try them all:

python · try it yourself
from itertools import combinations

items = [("tent", 6, 66), ("stove", 5, 50), ("camera", 5, 54), ("book", 2, 18)]
W = 10

best_value, best_set, checked = 0, (), 0
for k in range(len(items) + 1):
    for subset in combinations(items, k):
        checked += 1
        weight = sum(w for _, w, _ in subset)
        value = sum(v for _, _, v in subset)
        if weight <= W and value > best_value:
            best_value, best_set = value, subset
print("subsets checked:", checked)
print("best:", [name for name, _, _ in best_set], "value", best_value,
      "weight", sum(w for _, w, _ in best_set))
subsets checked: 16
best: ['stove', 'camera'] value 104 weight 10

For 40 items, 2⁴⁰ is over a trillion subsets. We need something smarter.

Greedy doesn't work

A tempting shortcut: take items in order of value per kilogram until the bag is full. It's fast, but it can miss the optimum:

python · try it yourself
items = [("tent", 6, 66), ("stove", 5, 50), ("camera", 5, 54), ("book", 2, 18)]
W = 10

ranked = sorted(items, key=lambda it: it[2] / it[1], reverse=True)
print("by value/kg:", [(name, round(v / w, 1)) for name, w, v in ranked])
taken, room = [], W
for name, w, v in ranked:
    if w <= room:
        taken.append(name)
        room -= w
print("greedy takes:", taken, "value", sum(v for n, w, v in items if n in taken))
by value/kg: [('tent', 11.0), ('camera', 10.8), ('stove', 10.0), ('book', 9.0)]
greedy takes: ['tent', 'book'] value 84

Greedy grabs the tent first (the best ratio, 11 per kg). Then neither the camera nor the stove fits in the remaining 4 kg, so it ends with tent + book = 84. The brute force above found a better choice: stove + camera = 104, using the full 10 kg. Greedy is optimal for the fractional knapsack, where items can be cut, but not for 0/1.

Dynamic programming

Define best[i][c] = the maximum value using only the first i items with capacity c. For item i (weight w, value v) there are only two choices:

  • skip it: best[i-1][c]
  • take it (if it fits): v + best[i-1][c - w]
text
best[i][c] = max(best[i-1][c],  v + best[i-1][c-w])   if w <= c
best[i][c] = best[i-1][c]                              otherwise

with best[0][c] = 0 (no items, no value). Filling the table row by row gives the answer in best[n][W]:

python · try it yourself
items = [("tent", 6, 66), ("stove", 5, 50), ("camera", 5, 54), ("book", 2, 18)]
W = 10
n = len(items)
best = [[0] * (W + 1) for _ in range(n + 1)]

for i in range(1, n + 1):
    name, w, v = items[i - 1]
    for c in range(W + 1):
        best[i][c] = best[i - 1][c]
        if w <= c:
            best[i][c] = max(best[i][c], v + best[i - 1][c - w])

print("capacity:  " + " ".join(f"{c:>3}" for c in range(W + 1)))
print("(none)     " + " ".join(f"{x:>3}" for x in best[0]))
for i in range(1, n + 1):
    print(f"+{items[i - 1][0]:<9} " + " ".join(f"{x:>3}" for x in best[i]))
print("maximum value:", best[n][W])
capacity:    0   1   2   3   4   5   6   7   8   9  10
(none)       0   0   0   0   0   0   0   0   0   0   0
+tent        0   0   0   0   0   0  66  66  66  66  66
+stove       0   0   0   0   0  50  66  66  66  66  66
+camera      0   0   0   0   0  54  66  66  66  66 104
+book        0   0  18  18  18  54  66  72  84  84 104
maximum value: 104

Each row adds one more item to choose from. The bottom-right cell is the answer.

Which items?

The table stores values, not choices, but we can trace back from best[n][W]: if the value changed when item i was added, item i was taken.

python · try it yourself
items = [("tent", 6, 66), ("stove", 5, 50), ("camera", 5, 54), ("book", 2, 18)]
W = 10
n = len(items)
best = [[0] * (W + 1) for _ in range(n + 1)]
for i in range(1, n + 1):
    _, w, v = items[i - 1]
    for c in range(W + 1):
        best[i][c] = best[i - 1][c]
        if w <= c:
            best[i][c] = max(best[i][c], v + best[i - 1][c - w])

c, chosen = W, []
for i in range(n, 0, -1):
    if best[i][c] != best[i - 1][c]:     # value changed: item i was taken
        name, w, _ = items[i - 1]
        chosen.append(name)
        c -= w
print("take:", chosen[::-1], "value", best[n][W], "weight", W - c)
take: ['stove', 'camera'] value 104 weight 10

Complexity

The table has (n + 1) × (W + 1) cells, each filled in O(1): O(n · W) time and memory. That's far better than 2ⁿ for moderate capacities. It's called pseudo-polynomial, because it depends on the numeric value W, not just the number of items: capacities in the billions would make the table too large.

Tip: Only the previous row is ever read, so you can use a single 1-D list and loop c downwards from W to w. Looping upwards would let an item be taken twice (that's the unbounded knapsack).

Test yourself

What does "0/1" in 0/1 knapsack mean?

  1. Values are 0 or 1
  2. Each item is either taken whole or not at all
  3. The capacity is 1
  4. Only one item can be taken

Why does sorting by value per kilogram fail for the 0/1 knapsack?

  1. It is too slow
  2. Taking the best-ratio items first can waste capacity that a different combination would use better
  3. It only works for integers
  4. It always takes every item

What is the time complexity of the DP solution with n items and capacity W?

  1. O(2ⁿ)
  2. O(n log n)
  3. O(n · W)
  4. O(W²)