Sub topic 2
The Greedy Paradigm and the Greedy-Choice Property
This chapter assumes you know Big-O notation, how to sort and use a binary heap, and how to read short Python. It builds the working model you need before the later chapters that prove specific greedy algorithms correct.
What a greedy algorithm does
A greedy algorithm builds a solution one step at a time. At each step it takes the choice that looks best right now, according to a fixed rule. It never reconsiders an earlier choice.
This is cheap. Most greedy algorithms are a sort or a heap plus one pass, so they run in O(n log n) or better. The cost is that the rule can be wrong, so a greedy algorithm needs a correctness argument. A solution that merely looks sensible is not enough.
A typical greedy algorithm has this shape:
- Define a rule that ranks the candidate choices (for example, earliest finish time or highest value per unit weight).
- Order the candidates by that rule, using sorting or a priority queue.
- Scan the candidates. Keep a candidate if it is feasible with what you have already kept, and discard it otherwise.
- Stop when no candidates remain or the solution is complete.
Two properties that make greedy work
A greedy algorithm is correct for a problem when both properties below hold.
- Optimal substructure. After you make a choice, the remaining problem is a smaller instance of the same problem. An optimal solution to the whole problem contains an optimal solution to that smaller instance. Dynamic programming also needs this property.
- Greedy-choice property. Some optimal solution contains the choice the rule picks first. You can commit to that choice without looking at any subproblem solution.
The second property separates greedy from dynamic programming. Dynamic programming tries every first choice and compares the results. Greedy proves that one particular first choice is safe and skips the comparison. The next chapter covers the exchange argument, which is the standard way to prove this.
When the rule fails
Greedy coin change takes the largest coin that fits, repeatedly. For US coins it is optimal. For other coin sets it is not.
def greedy_coins(coins, amount):
count = 0
for c in sorted(coins, reverse=True):
count += amount // c
amount %= c
return count if amount == 0 else None
def best_coins(coins, amount):
INF = float('inf')
dp = [0] + [INF] * amount
for a in range(1, amount + 1):
for c in coins:
if c <= a and dp[a - c] + 1 < dp[a]:
dp[a] = dp[a - c] + 1
return dp[amount] if dp[amount] != INF else None
print(greedy_coins([1, 3, 4], 6), best_coins([1, 3, 4], 6)) # 3 2
print(greedy_coins([25, 10, 5, 1], 63), best_coins([25, 10, 5, 1], 63)) # 6 6With coins {1, 3, 4} and amount 6, greedy takes 4 first and then needs two 1s, for 3 coins. The optimum is 3 + 3, which uses 2 coins. The choice "take the 4" is not part of any optimal solution, so the greedy-choice property fails. With {25, 10, 5, 1} the largest coin is always safe, and both functions agree.
A single counterexample is enough to show a greedy rule is wrong. A correctness proof needs an argument that covers every input.
Deciding in practice
In a timed exam, test the rule on instances with three to five items before trusting it. Pay attention to ties and to cases where the best item barely fits.
Complexity of a typical greedy algorithm
The running time usually comes from the ordering step. Sorting n candidates costs O(n log n), and the scan costs O(n). Together that is O(n log n). When the algorithm uses a heap instead (as Huffman coding does), each of the n heap operations costs O(log n), which gives the same bound. Extra feasibility checks add to this. If a check costs O(n) per candidate, the whole algorithm becomes O(n²).
Common errors
- Choosing a plausible rule without testing it. Several rules can sound reasonable. For scheduling, "shortest duration first" and "fewest conflicts first" both fail on some inputs, while "earliest finish first" is correct.
- Assuming a greedy result is the only optimum. Ties can produce different optimal solutions of equal value. The greedy-choice property says some optimal solution contains the choice, not that all of them do.
- Using greedy where items cannot be split. Value-per-weight greedy is optimal for fractional knapsack and not for 0/1 knapsack. Indivisibility is what breaks the property.
- Forgetting the feasibility check. The rule ranks candidates, but you still have to confirm each one fits the current partial solution.
- Treating a proof by example as a proof. Passing three tests does not establish correctness.
Exercises
Exercise
Coins are {1, 5, 6, 9} and the amount is 11. What does greedy (largest coin first) return, and what is the optimum?
Show answer
Greedy takes 9, then 1 and 1, for 3 coins. The optimum is 5 + 6, which uses 2 coins. The rule fails, so the greedy-choice property does not hold for this coin set.
Exercise
A greedy algorithm sorts n items in O(n log n) and then scans them, doing an O(log n) heap update for each item kept. What is the total running time?
Show answer
The scan costs O(n log n) in the worst case, since each of at most n items triggers one O(log n) update. Added to the O(n log n) sort, the total is O(n log n).
Exercise
State the difference between optimal substructure and the greedy-choice property.
Show answer
Optimal substructure means an optimal solution contains optimal solutions to its subproblems. The greedy-choice property means some optimal solution contains the greedy rule's first pick, so you can commit to it without comparing alternatives. Dynamic programming needs only the first property. Greedy needs both.