Greedy Algorithms vs Dynamic Programming: When Greedy Works
A greedy algorithm builds a solution one step at a time, takes whatever looks most attractive at each step, and never reconsiders. Dynamic programming (DP) also builds a solution from smaller pieces, but it considers every choice at each step and keeps the optimal result for each subproblem. Greedy is usually faster and shorter to write. The catch is that it is only correct for problems with a specific structure, and on many problems it quietly returns a worse answer.
This guide shows what that structure is, gives problems on both sides of the line, and ends with a practical way to test a greedy idea. Examples use Python 3.10 or later and only the standard library.
Two properties
Optimal substructure: an optimal solution to the problem contains optimal solutions to its subproblems. If the cheapest way to make 6 cents uses a 3-cent coin, the rest of it must be the cheapest way to make 3 cents. Both greedy algorithms and DP depend on this.
The greedy-choice property: there is always an optimal solution that starts with the locally optimal choice. Then you can make that choice, commit to it, and solve the one subproblem that is left. Greedy is correct only when the problem has this property, and showing that it does takes an argument, usually an exchange argument: take any optimal solution, swap in the greedy choice, and show the result is no worse.
DP needs only optimal substructure. Since it does not know which choice is right, it tries them all and stores the optimal answer for each subproblem, so that overlapping subproblems are solved once. If DP is new to you, dynamic programming explained builds it up from Fibonacci.
Where greedy fails: making change
To make an amount with the fewest coins, the obvious greedy rule is: take the largest coin that fits, repeat. With coins {1, 3, 4} and amount 6, that takes 4, then 1, then 1, three coins. But 3 + 3 uses two. The first choice (the 4) was the mistake, and greedy never revisits it.
The DP version defines best[a] as the fewest coins that make amount a, with best[0] = 0, and fills the table upward: best[a] is 1 plus the minimum of best[a - c] over every coin c that fits. It tries every last coin instead of guessing.
def greedy_coins(coins, amount):
used = []
for c in sorted(coins, reverse=True):
while amount >= c:
amount -= c
used.append(c)
return used
def dp_coins(coins, amount):
inf = float("inf")
best = [0] + [inf] * amount # best[a] = fewest coins for amount a
last = [None] * (amount + 1)
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
last[a] = c
used = []
while amount > 0:
used.append(last[amount])
amount -= last[amount]
return used
for coins, amount in [([1, 3, 4], 6), ([1, 5, 10, 25], 63)]:
g, d = greedy_coins(coins, amount), dp_coins(coins, amount)
print(coins, amount, "greedy:", g, len(g), "dp:", d, len(d))
fails = [a for a in range(1, 21)
if len(greedy_coins([1, 3, 4], a)) != len(dp_coins([1, 3, 4], a))]
print("greedy is not optimal for amounts:", fails)
[1, 3, 4] 6 greedy: [4, 1, 1] 3 dp: [3, 3] 2
[1, 5, 10, 25] 63 greedy: [25, 25, 10, 1, 1, 1] 6 dp: [1, 1, 1, 10, 25, 25] 6
greedy is not optimal for amounts: [6, 10, 14, 18]
With US-style coins {1, 5, 10, 25} and amount 63, greedy and DP both use 6 coins (two quarters, a dime and three pennies, in some order). For that coin set greedy is optimal for every amount, but that is a property of the particular coin set, and it has to be proved, not assumed. Adding one coin can break it, as {1, 3, 4} shows.
The last line is the most useful one. Comparing greedy with DP for every amount from 1 to 20 shows exactly where greedy loses: 6, 10, 14 and 18. For 10, greedy gives 4 + 4 + 1 + 1 (four coins) while 4 + 3 + 3 uses three.
The DP costs O(k x amount) time for k coin types (amount + 1 states, k choices each) and O(amount) space; see dynamic programming time complexity for how to count that in general.
Where greedy works: activity selection
Given activities with start and finish times, choose as many as possible that do not overlap. Several greedy rules sound plausible: shortest activity first, earliest start first, fewest conflicts first. The one that is correct is earliest finish time first: sort by finish time and take each activity that starts no earlier than the last chosen one finishes.
from itertools import combinations
activities = [(1, 4), (3, 5), (0, 6), (5, 7), (3, 9), (5, 9),
(6, 10), (8, 11), (8, 12), (2, 14), (12, 16)]
def select_by_finish(acts):
chosen, free_at = [], float("-inf")
for start, finish in sorted(acts, key=lambda a: a[1]):
if start >= free_at:
chosen.append((start, finish))
free_at = finish
return chosen
def brute_force(acts):
for size in range(len(acts), 0, -1):
for combo in combinations(sorted(acts), size):
if all(a[1] <= b[0] for a, b in zip(combo, combo[1:])):
return size
return 0
print(select_by_finish(activities))
print("greedy:", len(select_by_finish(activities)), "brute force:", brute_force(activities))
[(1, 4), (5, 7), (8, 11), (12, 16)]
greedy: 4 brute force: 4
The exchange argument is short. Let f be the activity that finishes first. Take any optimal schedule and replace its first activity with f. Since f finishes no later, it cannot overlap anything the schedule's first activity did not overlap, so the new schedule is still valid and just as large. So some optimal schedule starts with f, which is the greedy-choice property, and the same argument repeats on the activities that start after f ends. The brute-force check above confirms 4 on this input, but the proof is what covers every input.
The cost is the sort, O(n log n), followed by one O(n) pass. The Interview Complexity Estimator's rules table gives the same reading for "sorting the input" plus "single pass": O(n log n) time, and O(n) space from its sorting row.
Knapsack: fractional versus 0/1
A knapsack holds weight 50. The items, as (value, weight), are (60, 10), (100, 20) and (120, 30), with value per unit weight 6, 5 and 4.
- In the fractional knapsack you may take part of an item. Greedy by value per unit weight is optimal: take all of the first two items (weight 30, value 160), then 20/30 of the third (value 80), for 240.
- In the 0/1 knapsack each item is taken whole or not at all. The same greedy rule takes the first two items, then cannot fit the third, and stops at 160. The optimal answer is the second and third items, weight 50, value 220.
items = [(60, 10), (100, 20), (120, 30)] # (value, weight)
capacity = 50
def fractional(items, capacity):
total = 0.0
for value, weight in sorted(items, key=lambda i: i[0] / i[1], reverse=True):
take = min(weight, capacity)
total += value * take / weight
capacity -= take
return total
def greedy_01(items, capacity):
total = 0
for value, weight in sorted(items, key=lambda i: i[0] / i[1], reverse=True):
if weight <= capacity:
total += value
capacity -= weight
return total
def dp_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]
print("fractional, greedy by ratio:", fractional(items, capacity))
print("0/1, greedy by ratio: ", greedy_01(items, capacity))
print("0/1, dynamic programming: ", dp_01(items, capacity))
fractional, greedy by ratio: 240.0
0/1, greedy by ratio: 160
0/1, dynamic programming: 220
The fractional version has the greedy-choice property because any leftover capacity can be filled with the highest remaining ratio. The 0/1 version does not, because taking the highest-ratio item can leave capacity that no remaining combination fills well. The 0/1 DP runs in O(nW) for n items and capacity W; that bound is pseudo-polynomial, which the DP complexity guide linked above explains.
More greedy algorithms that are correct
- Kruskal's and Prim's algorithms for minimum spanning trees: always add the lightest safe edge. The cut property is their greedy-choice proof (see minimum spanning trees).
- Dijkstra's algorithm: always finish the closest unfinished vertex. Correct only with non-negative edge weights; one negative edge breaks the proof and the answer.
- Huffman coding: repeatedly merge the two least frequent symbols.
Greedy or DP?
| Greedy | Dynamic programming | |
|---|---|---|
| Choices per step | One, never revisited | All, the optimal one kept per subproblem |
| Requires | Greedy-choice property and optimal substructure | Optimal substructure (overlapping subproblems make it pay off) |
| Typical cost | A sort plus one pass | Number of states x work per state |
| Risk | Silently suboptimal if the property fails | Slower, more memory |
How to test a greedy idea
- Try to break it by hand. Spend a few minutes looking for a small counterexample: two or three items, coins, intervals. Most wrong greedy rules fail on something tiny, like amount 6 above.
- Compare against brute force. Write an exhaustive or DP solution that is obviously correct and slow, run both on many small inputs (random ones with a fixed
random.seed, or every amount up to 20 as above), and stop at the first disagreement. - If nothing breaks, look for the exchange argument. Testing finds bugs; only a proof shows there are none. If you cannot find the argument, treat the greedy rule as a guess and keep the DP.
Check yourself
- Coins {1, 5, 6, 9}, amount 11. What does greedy give, and what is optimal? (Greedy: 9 + 1 + 1, three coins. Optimal: 5 + 6, two coins.)
- Why does "shortest activity first" fail? (A short activity can sit across the boundary of two longer ones that do not overlap each other, so taking it blocks both: for example (0, 5), (4, 7), (6, 10).)