awelgorithms

0/1 knapsack

Updated

Each item at most once. dp[i][w] = max(dp[i-1][w], dp[i-1][w-a[i]]+v[i]) when a[i]<=w. Use v=a for these drills so value equals weight. Scanning one row left-to-right would reuse the item.

What to focus on

n items, capacity W. Answer dp[n][W]. Item 9 with W=5 is always skip. Item 1 then 4 fills W=5 exactly.

Worked examples

W=5 takes 1 and 4

a = [1, 4, 9], W = 5
  1. skip 9
  2. take 4 and 1
  3. value 5

Result: 5

W=10 takes 1 and 9

a = [1, 4, 9], W = 10
  1. 1+9=10 beats 1+4=5 and 9

Result: 10

W=3 takes 1

a = [1, 4, 9], W = 3
  1. 4 and 9 too heavy
  2. take 1

Result: 1

Try it

Write knapsack01(a, W). a is item weights. W is capacity. value equals weight. dp[i][w] is max value using each of the first i items at most once with capacity w. Each weight is used at most once. Return dp[n][W]. W=5 → 5. W=10 → 10. W=3 → 1.

Capacity W and item weights are positive. n = 3. value equals weight. A feasible packing exists.