The greedy choice
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?
A greedy algorithm makes the choice that looks best right now and never takes it back. Here: the most dollars per kilogram first. A earns $6/kg, B $5/kg, C $4/kg, so the code sorts them A, B, C.
A fits, so the loop takes all 10 kg of it: take = min(10, 50) = 10. The bag now holds 10 kg worth $60, with 40 kg of room left.
B is next best. All 20 kg fit too. The bag holds 30 kg worth $160, and 20 kg of room is left.
C weighs 30 kg, but only 20 kg of room is left. In this version items can be cut, like flour, so take = min(30, 20) = 20: two thirds of C, worth $80. The bag is full and worth $240.
The exchange argument
Greedy never looked ahead, so we must prove it is right. Compare it with any other full bag, say all of B and all of C. It also weighs 50 kg, but it is worth $220, and A stays out.
Swap 10 kg of C ($4/kg) out for the 10 kg of A ($6/kg) left outside. The weight stays 50 kg and the value rises by $20, to $240. Trading toward a better $/kg never loses value.
Any full bag that holds worse kilograms while better ones sit outside can make such a swap without losing value. Repeating the swaps turns it into the greedy bag. So no bag is worth more than $240.
When greedy fails
Change one rule: each item goes in whole or not at all. This is the 0/1 knapsack. Greedy still takes A, then B: 30 kg, $160. C needs 30 kg, only 20 are left, so C stays out.
Yet B and C, leaving A out, weigh exactly 50 kg and are worth $220, more than $160. The swap trick breaks: you cannot trade 10 kg of C without taking all 30. This version needs dynamic programming instead.
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.