ENع
←0/1 knapsack
Lesson 40 · Dynamic programming and backtracking

The knapsack problem

14 min9 steps5 questionsAdvanced
About this lesson

A bag holds 5 kg and three items compete for the space. Greedy by value per kg picks wrong, and trying every subset doubles the work with each new item. A table of small questions, best[i][c], solves it: each cell decides once about one item, skip it or take it. Watch the 24 cells fill, walk back from the corner to find the items, and see why the cost O(nW) is called pseudo-polynomial. It uses the state-and-transition recipe from "Defining states and transitions", and the Software lesson "Dynamic programming" covers memoisation and tables.

You'll learn to

Tick what you feel confident about. These self-checks do not affect your lesson score.

Fig 40 · Interactive
01 / 09

Pack a bag

A bag holds 5 kg. Item A weighs 1 kg and is worth $2, B weighs 3 kg for $4, C weighs 4 kg for $5. Each item goes in whole or not at all: the 0/1 knapsack. Goal: the most value.

capacity W = 5 kg, n = 3 items
  A  1 kg  $2   $2.00 per kg
  B  3 kg  $4   $1.33 per kg
  C  4 kg  $5   $1.25 per kg
take each item whole (1) or not at all (0)
maximise total value, total weight ≤ 5
Loading figure…
or ← →
Read the lesson step by step
  1. Pack a bag

    A bag holds 5 kg. Item A weighs 1 kg and is worth $2, B weighs 3 kg for $4, C weighs 4 kg for $5. Each item goes in whole or not at all: the 0/1 knapsack. Goal: the most value.

    capacity W = 5 kg, n = 3 items
      A  1 kg  $2   $2.00 per kg
      B  3 kg  $4   $1.33 per kg
      C  4 kg  $5   $1.25 per kg
    take each item whole (1) or not at all (0)
    maximise total value, total weight ≤ 5
  2. Greedy picks wrong

    Greedy by value per kg takes A, then B: $6, and C no longer fits. Yet A + C weighs exactly 5 kg and is worth $7. Trying all 2ⁿ subsets finds it, but doubles the work with every new item.

    greedy: best $ per kg first, whole items only
      A $2.00/kg  take   room 5 → 4
      B $1.33/kg  take   room 4 → 1
      C $1.25/kg  4 kg > 1 kg left: skip
      greedy total $6
    
    brute force: 8 subsets, best A + C = $7
    30 items would mean 2³⁰ = 1,073,741,824 subsets
  3. One cell per small question

    Let best[i][c] be the most value from the first i items in a bag of c kg. The table has rows 0, A, B, C (items up to that one) and columns 0 to 5 kg. No items or no room is worth $0.

    state: best[i][c] = most value using items 1..i
           with capacity c
    rows    i = 0, 1 (A), 2 (B), 3 (C)
    columns c = 0, 1, 2, 3, 4, 5
    4 × 6 = 24 cells
    base cases: best[0][c] = 0, best[i][0] = 0
    
    >>> [[0] * (5 + 1)]
    [[0, 0, 0, 0, 0, 0]]
  4. Skip it or take it

    Each cell decides about one item. Skip it: keep the cell straight above. Take it, if it fits: its value plus the cell above and w columns left. Keep the larger. Row A at 1 kg: max(0, 2 + 0) = 2.

    best[i][c] = max(
        best[i-1][c],              # skip item i
        v_i + best[i-1][c - w_i])  # take it, if w_i ≤ c
    
    best[A][1] = max(best[0][1], 2 + best[0][0])
               = max(0, 2 + 0) = 2
    each cell reads only the row above
  5. Fill row A

    The rest of row A: from 1 kg up, item A always fits, so each cell is max(0, 2 + 0) = 2. With only item A to choose from, the best you can do is $2, whatever the bag size.

    row A (w = 1, v = 2)
      c=1: max(0, 2 + 0) = 2
      c=2: max(0, 2 + 0) = 2
      c=3: max(0, 2 + 0) = 2
      c=4: max(0, 2 + 0) = 2
      c=5: max(0, 2 + 0) = 2
    best[A] = [0, 2, 2, 2, 2, 2]
  6. Fill row B

    B weighs 3 kg, so at 1 and 2 kg it cannot fit: copy the cell above. At 3 kg, taking B gives 4 + 0 = 4. At 4 kg, 4 + best[A][1] = 4 + 2 = 6: B and A together.

    row B (w = 3, v = 4)
      c=1: 3 > 1, skip only     = 2
      c=2: 3 > 2, skip only     = 2
      c=3: max(2, 4 + 0) = 4
      c=4: max(2, 4 + 2) = 6
      c=5: max(2, 4 + 2) = 6
    best[B] = [0, 2, 2, 4, 6, 6]
  7. Fill row C

    C weighs 4 kg. At 4 kg, taking C gives 5 + 0 = 5, less than the 6 above, so skip it. At 5 kg, 5 + best[B][1] = 5 + 2 = 7 beats 6. The corner cell holds the answer: $7.

    row C (w = 4, v = 5)
      c=1: 4 > 1, skip only     = 2
      c=2: 4 > 2, skip only     = 2
      c=3: 4 > 3, skip only     = 4
      c=4: max(6, 5 + 0) = 6
      c=5: max(6, 5 + 2) = 7
    best[C] = [0, 2, 2, 4, 6, 7]
    answer best[C][5] = 7
  8. Walk back to the items

    Which items? Start at the corner. 7 differs from the 6 above, so C was taken: go up and 4 columns left. 2 equals the 2 above, so B was skipped. 2 differs from 0, so A was taken: A + C, $7.

    walk back from best[C][5]
      best[C][5] = 7 ≠ best[B][5] = 6  → take C, c = 5 − 4 = 1
      best[B][1] = 2 = best[A][1] = 2  → skip B
      best[A][1] = 2 ≠ best[0][1] = 0  → take A, c = 1 − 1 = 0
    bag: A + C, 1 + 4 = 5 kg, $2 + $5 = $7
  9. Cost: n times W

    The table has (n + 1)(W + 1) = 4 × 6 = 24 cells, each one max, so the time is O(nW). That is pseudo-polynomial: W is a number, and one more digit in W makes the table ten times wider.

    cells: (n + 1)(W + 1) = 4 × 6 = 24
    work per cell: one max → O(1)
    time  O(nW), space O(nW) for the full table
          (O(W) if you keep one row and run c downward)
    input size: n items + about log₂ W bits for W
    W = 5 → 6 columns; W = 50,000 → 50,001 columns
    
    >>> knapsack([(1, 2), (3, 4), (4, 5)], 5)[-1][-1]
    7

Quiz Unlocks after the last step.