10 kg · $60$6 per kg20 kg · $100$5 per kg1def greedy(items, cap):2 items.sort(key=rate,3 reverse=True)4 got = 05 for w, v in items:6 take = min(w, cap)7 got += v * take / w8 cap -= take9 return got30 kg · $120$4 per kg1020304050 kgkg0$$0
Slabs: 10 kg each; A $6/kg, B $5/kg, C $4/kgThe bag: a scale up to 50 kgA hopping slab: one greedy choice (or one swap)Each slab is 10 kg. Greedy takes the best dollars per kilogram first: all of A, all of B, then 20 kg cut from C, for $240. Swapping one C slab in a rival bag for A gains $20: that exchange argument proves no bag beats greedy when items can be cut. With whole items only, greedy stops at $160 while B and C give $220.

The greedy choice

  1. A bag holds at most 50 kg. Item A weighs 10 kg and is worth $60, B weighs 20 kg for $100, C weighs 30 kg for $120. All three weigh 60 kg, too much. Which load is worth the most?

The exchange argument

When greedy fails

What happens

;; step 1/10 · problem
capacity 50 kg
  A  10 kg  $ 60
  B  20 kg  $100
  C  30 kg  $120
all three: 60 kg > 50 kg

bag: empty  →  0 kg, $0

The three items and the 50 kg bag are the example CLRS (Introduction to Algorithms) uses for the fractional and 0/1 knapsack problems; the book measures them in pounds. The exchange argument in general: take any optimal answer that differs from the greedy one, change one part of it toward the greedy choice, and show the value does not get worse. Repeat until the two are the same. This proves the greedy-choice property; optimal substructure (what is left is a smaller problem of the same kind) finishes the proof.