Dynamic Programming21 sections · 916 units
Open in Course

0/1 Knapsack - Why Greedy Fails

The trap

You might think: "Just sort by value and grab items until the bag is full." Try it on this example: Items: (weight=1weight=1, value=1value=1), (weight=3weight=3, value=4value=4), (weight=4weight=4, value=5value=5), (weight=5weight=5, value=7value=7).

Capacity W=7W = 7. Greedy by value picks the most valuable item first: (weight=5weight=5, value=7value=7). Remaining capacity is 2. The only item that fits is (weight=1weight=1, value=1value=1). Total value: 7+1=87 + 1 = 8.

But taking items (weight=3weight=3, value=4value=4) and (weight=4weight=4, value=5value=5) gives 4+5=94 + 5 = 9 with total weight 3+4=73 + 4 = 7. The greedy approach misses this better combination. You need DP to explore all possibilities efficiently.