Sub topic 1
What Makes an Algorithm Greedy
A greedy algorithm builds a solution one piece at a time. At each step it takes the option that looks best right now and never goes back to change that choice. This chapter gives you the working model you will use in the rest of the tutorial and shows how greedy differs from the other two common ways to solve optimization problems.
Prerequisites
This chapter assumes you can:
- Write Python functions and loops.
- Read Big-O notation and know that sorting costs O(n log n).
- Follow a short proof by induction or contradiction. You will need this in later chapters more than in this one.
The Shape of a Greedy Algorithm
Most greedy algorithms follow the same template:
- Pick a rule that ranks the remaining options, such as "cheapest first" or "earliest deadline first."
- Take the best-ranked option if it keeps the partial solution valid.
- Repeat until no options remain.
A greedy algorithm only ever makes a choice and commits to it. It doesn't backtrack, and it doesn't compare whole solutions. Most of the work is usually the sort or the priority queue that produces the ranking, so greedy algorithms often run in O(n log n).
A Worked Example
Suppose you want to buy as many items as possible with a fixed budget. The greedy rule is to buy the cheapest item first. The code below compares that rule with exhaustive search, which tries every subset.
from itertools import combinations
def greedy_max_items(prices, budget):
bought = []
for p in sorted(prices):
if p > budget:
break
bought.append(p)
budget -= p
return bought
def brute_force_max_items(prices, budget):
for k in range(len(prices), 0, -1):
for combo in combinations(prices, k):
if sum(combo) <= budget:
return list(combo)
return []
prices = [7, 2, 9, 4, 3, 8]
print(greedy_max_items(prices, 15)) # [2, 3, 4]
print(len(brute_force_max_items(prices, 15))) # 3Both approaches find 3 items, but they do very different amounts of work. The greedy version sorts once and makes a single pass, which is O(n log n). The brute-force version can check up to 2^n subsets.
Greedy, Exhaustive Search, and Dynamic Programming
| Approach | How it decides | Typical cost | Guarantees optimum? |
|---|---|---|---|
| Exhaustive search | Tries every candidate solution | Exponential | Yes |
| Dynamic programming | Solves and stores all relevant subproblems, then combines them | Polynomial, often O(n²) or O(n·W) | Yes, if subproblems overlap and combine correctly |
| Greedy | Makes one locally best choice per step and keeps it | Often O(n log n) | Only when the problem has the right structure |
Dynamic programming keeps every subproblem's answer open until it has compared them. Greedy commits right away. That makes greedy faster and simpler to write, but it is correct only for certain problems.
Common Errors
- Wrong ranking rule. Several rules can sound reasonable, and often only one of them is correct.
- Assuming correctness from a few tests. Small hand-picked inputs rarely expose a bad rule. Compare against brute force on random inputs.
- Using greedy where choices interact. If an early choice changes which later options are worth taking, greedy may need to be replaced by dynamic programming.
The next two chapters name the two properties that make greedy correct: the greedy choice property and optimal substructure.
Exercise
You want to fit as many files as possible onto a disk of capacity C, where each file has a size. Describe the greedy rule, state its running time, and say which rule from this chapter's example it matches.
Show answer
Sort the files by size in ascending order and add each one while it still fits. Sorting dominates, so the running time is O(n log n). This is the same "cheapest first" rule as the budget example, with file size playing the role of price.
Exercise
In one sentence, what does a greedy algorithm never do that dynamic programming routinely does?
Show answer
A greedy algorithm never stores and compares alternative answers to subproblems before committing, because it keeps its first locally best choice.