Sub topic 1
What Makes an Algorithm Greedy
A greedy algorithm builds a solution one step at a time. At each step it takes the choice that looks best right now and never undoes it. Exhaustive search tries every combination. Dynamic programming compares the answers to many subproblems. A greedy algorithm commits to one choice and moves on, so it is usually fast, often a sort followed by a single pass.
Prerequisites
This chapter assumes you can:
- Write Python functions and loops.
- Read Big-O notation.
- Follow a proof by induction.
The Greedy Choice Property
A problem has the greedy choice property when some optimal solution begins with the greedy choice. If that holds, taking the locally best option never rules out every optimal answer.
Optimal Substructure
A problem has optimal substructure when an optimal solution contains optimal solutions to its subproblems. After the greedy choice, what remains is a smaller instance of the same problem. A greedy algorithm is correct when both properties hold. Dynamic programming relies on optimal substructure alone.
When Greedy Fails: Coin Change
The coin change problem asks for the fewest coins that add up to an amount. The greedy strategy takes the largest coin that still fits, as many times as it can.
def greedy_coins(coins, amount):
used = []
for c in sorted(coins, reverse=True):
while amount >= c:
amount -= c
used.append(c)
return used if amount == 0 else None
print(greedy_coins([1, 5, 10, 25], 63)) # [25, 25, 10, 1, 1, 1]
print(greedy_coins([1, 3, 4], 6)) # [4, 1, 1], but [3, 3] uses only 2 coinsWith the coins {1, 3, 4}, taking the 4 first is a mistake: no optimal solution for 6 starts with 4. The greedy choice property fails here. One counterexample is enough to show that a greedy strategy is wrong.
Proving Correctness: Greedy Stays Ahead
The greedy-stays-ahead technique compares the greedy solution with any optimal solution step by step:
- Choose a measure of progress, for example "the finish time of the k-th chosen item."
- Prove by induction that after every step k, the greedy measure is at least as good as the optimal one.
- Conclude that greedy cannot end up behind, so its final answer is optimal.
Exercise
With coins {1, 5, 6, 9} and amount 11, what does the greedy algorithm return, and is it optimal?
Show answer
Greedy returns [9, 1, 1], which is 3 coins. The optimal answer is [5, 6], which is 2 coins, so greedy is not optimal.
Exercise
Which two properties must a problem have for a greedy algorithm to be correct?
Show answer
The greedy choice property, meaning some optimal solution starts with the greedy choice, and optimal substructure, meaning the rest of the solution is an optimal solution to the remaining subproblem.