Sub topic 14
Greedy or Dynamic Programming? Choosing the Right Tool
This chapter assumes you have worked through the earlier chapters on the greedy choice property, optimal substructure, and the exchange argument. It also assumes you can read a bottom-up dynamic programming (DP) table, meaning an array where each entry stores the best answer to a smaller subproblem. You should be comfortable running Python and reading O(n log n) and O(nW) cost bounds.
Greedy algorithms and dynamic programming both depend on optimal substructure: an optimal solution contains optimal solutions to its subproblems. They differ in how many subproblems they look at before making a choice. A greedy algorithm commits to one choice and solves one remaining subproblem. DP considers every choice, solves the subproblem each choice leaves behind, and keeps the best result. Greedy is faster and simpler. DP is correct in more cases.
The Core Difference
At each step, a greedy algorithm asks: "Which option looks best right now?" A DP algorithm asks: "For each option, what is the best I can do afterwards?" Greedy works only when the first question always leads to the same answer as the second. That is the greedy choice property. DP needs only optimal substructure and a manageable number of distinct subproblems.
| Aspect | Greedy | Dynamic programming |
|---|---|---|
| Choices examined per step | One, the locally best | All of them |
| Subproblems solved per step | One | One per choice, usually memoized |
| Properties required | Greedy choice property and optimal substructure | Optimal substructure and overlapping subproblems |
| Typical cost | O(n log n), dominated by sorting | Number of subproblems times cost per subproblem, e.g. O(nW) for knapsack |
| Proof burden | High: needs stays-ahead or exchange argument | Low: the recurrence covers every case |
| Failure mode | Silently returns a suboptimal answer | Runs out of time or memory |
The last row matters most in practice. A wrong greedy algorithm does not crash. It returns plausible numbers that are sometimes too big or too small, and ordinary tests often miss this.
One Problem, Two Versions: Knapsack
The fractional knapsack chapter showed that taking items in order of value per weight is optimal when you may take part of an item. Now forbid splitting. Each item is either fully in or fully out. This is the 0/1 knapsack problem.
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 60 item (ratio 6) and the 100 item (ratio 5), which leaves 20 units of capacity. The 120 item weighs 30, so it no longer fits. The best answer skips the item with the highest ratio and takes 100 + 120 = 220.
Look at where the exchange argument breaks down. In the fractional version, you swap a small amount of a low-ratio item for the same weight of a high-ratio item, and the total value never drops. In the 0/1 version, you can't swap part of an item. Swapping a whole item can push the weight over capacity, or it can leave unused space that nothing else fits into. The proof needed divisibility. Once divisibility is gone, so is the greedy choice property.
The DP inner loop runs from high capacity down to low capacity so that each item is counted at most once. Running it upward would let best[c - weight] already include the same item, which solves the unbounded knapsack problem instead.
Signals That Point Toward Each Tool
Before you write any code, these features of a problem suggest which way to go.
Signals for greedy:
- Choices can be divided, as with fractions of items, flow, or time.
- One natural ordering (by finish time, deadline, ratio, or weight) makes every choice compatible with all later ones.
- Feasibility is preserved when you add elements, as in "acyclic" for spanning trees. The matroids chapter makes this precise.
- You can write a short exchange argument without special cases.
Signals for DP:
- A choice uses up a shared, indivisible resource, such as integer capacity or a coin amount, in amounts that vary from item to item.
- Elements have weights or values that compete with a structural rule. Weighted interval scheduling is the standard example. With weights, earliest finish time fails: a long interval worth 100 can overlap two short intervals worth 1 each.
- Your attempted exchange proof keeps needing "unless" clauses.
- Small random tests turn up a counterexample.
Test Before You Trust
When a proof is not obvious, compare the greedy algorithm against an exact solver on many small inputs. If the two disagree, you have a counterexample. If they agree on thousands of cases, you have evidence, though not proof, that greedy is worth trying to prove correct.
import random
def greedy_coin_count(coins, amount):
count = 0
for c in sorted(coins, reverse=True):
count += amount // c
amount %= c
return count if amount == 0 else None
def dp_coin_count(coins, amount):
INF = float("inf")
best = [0] + [INF] * amount
for a in range(1, amount + 1):
for c in coins:
if c <= a and best[a - c] + 1 < best[a]:
best[a] = best[a - c] + 1
return best[amount] if best[amount] != INF else None
def find_counterexample(coins, max_amount=200):
for amount in range(1, max_amount + 1):
g = greedy_coin_count(coins, amount)
d = dp_coin_count(coins, amount)
if g != d:
return amount, g, d
return None
print(find_counterexample([1, 5, 10, 25])) # None
print(find_counterexample([1, 3, 4])) # (6, 3, 2)
random.seed(7)
for _ in range(5):
system = sorted({1} | set(random.sample(range(2, 30), 3)))
print(system, find_counterexample(system))The random loop prints coin systems along with the first amount where greedy fails, or None. Most random systems fail. US-style denominations are a special case. Systems where greedy is always optimal are called canonical. For a system that contains 1, Kozen and Zaks (1994) showed that if any counterexample exists, the smallest one is less than the sum of the two largest coins. That turns the brute-force check above into an exact test: set max_amount to the sum of the two largest coins.
A Decision Procedure
The last branch matters. Some problems have neither a correct greedy rule nor a DP with a manageable number of states: set cover, 0/1 knapsack with very large capacities, and many scheduling variants. In those cases a greedy algorithm can still be the right tool if it comes with a proven bound on how far from optimal it can be. The next chapter covers that approach.
Common Errors
- Trusting the examples you made up. Hand-made tests tend to have the structure that makes greedy work. Use random tests.
- Copying a proof to a variant. Earliest finish time is proven for unweighted intervals only. Adding weights, deadlines, or setup costs changes the problem, so you need a new proof.
- Sorting by the wrong key. Sorting by start time or by shortest duration fails for activity selection, even though both sound reasonable. The key chosen is the algorithm.
- Assuming DP is always available. Check how many states the DP has before rejecting greedy. A memoized recursion over 10^12 states will not finish.
- Using DP where greedy is proven. This is correct but wasteful. An O(nW) table for fractional knapsack throws away an O(n log n) solution.
Exercise
A greedy rule for 0/1 knapsack takes items in decreasing order of value, ignoring weight. Give a two-item instance with capacity 10 where it fails, and state the optimal value.
Show answer
Items (value 10, weight 10) and (value 9, weight 1), but capacity 10 lets the optimum take only one heavy item, so add a third: (10, 10), (9, 5), (9, 5). Greedy takes the value-10 item and fills the knapsack, for a total of 10. The optimum takes both value-9 items, for a total of 18. (No two-item instance works with capacity 10 if both items fit together, so you need either three items or two items that cannot both fit, where the lighter item is worth more. For example, (10, 10) and (9, 1) with capacity 10 does not fail, because greedy takes 10 and the optimum is also 10.)
Exercise
In weighted interval scheduling, each interval has a value and you want the maximum total value of non-overlapping intervals. Explain why the exchange argument from unweighted activity selection fails, and name the DP subproblem that replaces it.
Show answer
The unweighted exchange swaps the first interval of an optimal solution for the interval that finishes earliest. That keeps the count the same, but it can lower the total value when the earliest-finishing interval is worth less. The DP sorts intervals by finish time and defines best[j] as the maximum value using only the first j intervals. Then best[j] = max(best[j-1], value[j] + best[p(j)]), where p(j) is the last interval that ends no later than interval j starts.
Exercise
Run find_counterexample on the coin system [1, 7, 10]. What does it return, and which pair of coins beats greedy?
Show answer
It returns (14, 5, 2). Greedy uses 10 + 1 + 1 + 1 + 1 (five coins), while 7 + 7 uses two coins. The value 14 is below 10 + 7 = 17, which matches the Kozen and Zaks bound on the smallest counterexample.