Sub topic 14
Greedy or Dynamic Programming? Choosing the Right Tool
This chapter assumes you know the greedy choice property and optimal substructure, the coin change counterexample, and the fractional knapsack algorithm from earlier chapters. You should also be able to read a simple bottom-up dynamic programming table.
The shared root
Greedy algorithms and dynamic programming (DP) both depend on optimal substructure: an optimal solution contains optimal solutions to its subproblems. They differ in how many subproblems they look at when they make a choice.
- A greedy algorithm commits to one choice and solves the single subproblem that choice leaves behind.
- A DP algorithm tries every choice, solves each resulting subproblem, and keeps the best result.
Greedy is only correct when the greedy choice property also holds, meaning some optimal solution starts with the locally best choice. When that property fails, you pay DP's extra cost to check every option.
| Aspect | Greedy | Dynamic programming |
|---|---|---|
| Choices examined per step | One | All |
| Needs greedy choice property | Yes | No |
| Typical cost | O(n log n) for sorting | O(n · W) or O(n²) table |
| Correctness proof | Stays ahead or exchange argument | Recurrence plus induction |
| Failure mode | Silently returns a suboptimal answer | Too slow or too much memory |
Same items, different rules
The fractional knapsack is greedy-optimal because you can always fill leftover capacity with part of the best-ratio item. Remove that freedom and the exchange argument breaks: swapping in a better-ratio item can leave unusable empty space.
def greedy_01(items, capacity):
total = 0
for value, weight in sorted(items, key=lambda it: it[0] / it[1], reverse=True):
if weight <= capacity:
total += value
capacity -= weight
return total
def knapsack_01(items, capacity):
best = [0] * (capacity + 1)
for value, weight in items:
for c in range(capacity, weight - 1, -1):
best[c] = max(best[c], best[c - weight] + value)
return best[capacity]
items = [(60, 10), (100, 20), (120, 30)]
print(greedy_01(items, 50)) # 160
print(knapsack_01(items, 50)) # 220Greedy takes the items with ratios 6 and 5, which leaves 20 units of space that the 30-unit item can't use. DP finds that skipping the best-ratio item and taking the other two scores 220. The inner loop runs downward so that each item is used at most once.
A decision procedure
In practice:
- Propose a greedy rule and spend a few minutes trying to break it on small inputs. Brute force over inputs of size 3 to 6 finds most counterexamples quickly.
- If no counterexample turns up, try to write an exchange argument. If the swap step won't go through, treat that as a warning sign.
- If greedy fails, write the DP recurrence. If the table is too large, as in NP-hard problems, a greedy approximation with a proven bound is often the best practical option.
Exercise
Write a DP that returns the minimum number of coins for an amount, and use it to show that greedy is wrong for coins {1, 3, 4} and amount 6.
Show answer
Let best[0] = 0 and best[a] = 1 + min(best[a - c]) over coins c <= a. In Python: best = [0] + [float("inf")] * amount; for a in range(1, amount + 1): best[a] = 1 + min(best[a - c] for c in coins if c <= a). For amount 6 this gives best[6] = 2 (3 + 3), while greedy returns [4, 1, 1], which is 3 coins.
Exercise
Activity selection and weighted activity selection (each interval has a value, maximize total value) look alike. Which one needs DP, and why?
Show answer
The weighted version needs DP. Taking the earliest-finishing interval is no longer safe, because a single long interval can be worth more than several short ones it overlaps. The exchange argument fails, so you sort by finish time and use the recurrence best[j] = max(best[j-1], value[j] + best[p(j)]), where p(j) is the last interval that ends before interval j starts.