The problem
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.
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.
The table
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.
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.
Filling it in
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.
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.
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.
Answer and cost
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.
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.
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.