Worked Examples: Greedy Algorithms

These examples are designed to step through the logical process of applying greedy algorithmic concepts.

Example 1: Activity Selection
❓ Problem: Given activities A1[1,4], A2[3,5], A3[0,6], A4[5,7], A5[3,9], find the maximum set of compatible activities.
💡 Solution: Sort by finish time: A1[1,4], A2[3,5], A4[5,7], A3[0,6], A5[3,9]. Select A1 (ends 4). Skip A2 (starts 3 < 4). Select A4 (starts 5 ≥ 4). Skip A3, A5. Result: {A1, A4}.
Example 2: Activity Selection Greedy Choice
❓ Problem: Why does "earliest finish time" work but "shortest duration" fails?
💡 Solution: Shortest duration can block multiple activities. Counter-example: [0,5], [4,5], [4,10]. Picking [4,5] (shortest) blocks both others. Earliest finish picks [0,5] then [4,10] = 2 activities.
Example 3: Fractional Knapsack
❓ Problem: W=50, Items: A(10kg, $60), B(20kg, $100), C(30kg, $120). Solve using greedy.
💡 Solution: Densities: A=$6/kg, B=$5/kg, C=$4/kg. Take all of A (10kg, $60). Take all of B (30kg total, $160). Take 20/30 of C (50kg total, $160 + $80 = $240).
Example 4: 0/1 Knapsack Greedy Fails
❓ Problem: Same items as above. Why doesn't greedy work for 0/1?
💡 Solution: Greedy: A + B = $160 (30kg). Optimal: B + C = $220 (50kg). Taking A wastes capacity.
Example 5: Coin Change (US Currency)
❓ Problem: Make 67 cents with US coins {25, 10, 5, 1}.
💡 Solution: Greedy works. 2×25=50, 1×10=60, 1×5=65, 2×1=67. Total: 6 coins.
Example 6: Coin Change (Greedy Fails)
❓ Problem: Make 6 cents with coins {1, 3, 4}.
💡 Solution: Greedy: 4+1+1 = 3 coins. Optimal: 3+3 = 2 coins. This coin system is not canonical.