awelgorithms

Unbounded knapsack

Updated

Each weight may be used many times. dp[w] = max over items a[i]<=w of dp[w-a[i]]+v[i]. Fill increasing w. Using the same row left-to-right is the usual 1D unbounded scan.

What to focus on

0/1 forbids reuse; unbounded allows 4+4. If the rec reads dp[i-1][w-a[i]] it is 0/1. If it reads dp[i][w-a[i]] (current row) it is unbounded.

Worked examples

three 4s

a = [1, 4, 9], W = 12
  1. 4+4+4=12
  2. 9+1+1+1=12 uses more items if counting coins
  3. value 12 when v=w

Result: 12

reuse 4 vs 0/1

a = [1, 4, 9], W = 8
  1. unbounded 4+4=8
  2. 0/1 cannot take 4 twice, best 1+4=5

Result: unbounded 8

W=3 all ones

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

Result: 3

Try it

Write unbounded(a, W). a is item weights. W is capacity. value equals weight. dp[w] is max value using any number of each item with capacity w. Name the current-row read that allows reuse. Contrast W=8 with 0/1. W=12 → 12. W=8 unbounded → 8 (0/1 would be 5). W=3 → 3.

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