0 kg1 kg2 kg3 kg4 kg5 kg0ABC1 kg$23 kg$44 kg$51def knapsack(items, cap):2 best = [[0] * (cap + 1)]3 for w, v in items:4 up = best[-1]5 row = up[:]6 for c in range(w, cap + 1):7 take = v + up[c - w]8 row[c] = max(up[c], take)9 best.append(row)10 return bestBAG · 5 KGABC
Back: the items (width = weight) and the 5 kg bag. Front: the table best[i][c]Blue token: skip the item, keep the cell above. Pink token: take it, add its value to the cell above and w leftGreen token: the walk back that recovers the itemsbest[i][c] is the most value from the first i items in a bag of c kg, one table cell per question. Each cell keeps the larger of skip (the cell above) and take (the item's value plus the cell above and w columns left), so the rows fill as 0 2 2 2 2 2, 0 2 2 4 6 6, 0 2 2 4 6 7. Walking back from the corner recovers the items: A + C, 5 kg, $7, where greedy by value per kg only reaches $6.

The problem

  1. 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.

The table

Filling it in

Answer and cost

What happens

;; step 1/9 · problem
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

The recurrence is the one in MIT 6.006 (Recitation 18) and in Sedgewick and Wayne's Knapsack.java: best[i][c] = max(best[i−1][c], v_i + best[i−1][c − w_i]), the second option only when w_i ≤ c, with best[0][c] = best[i][0] = 0. The code is real Python 3: knapsack([(1, 2), (3, 4), (4, 5)], 5) returns the four rows [0, 0, 0, 0, 0, 0], [0, 2, 2, 2, 2, 2], [0, 2, 2, 4, 6, 6] and [0, 2, 2, 4, 6, 7]. row = up[:] copies the row above, so cells with c < w keep the skip value.