Sub topic 1
What Makes an Algorithm Greedy
A greedy algorithm builds its answer one piece at a time. At each step it takes whichever option looks best right now and never goes back to change that decision. This chapter defines the paradigm, shows its parts in a small worked example, and compares it with exhaustive search and dynamic programming, the two approaches it is most often weighed against.
Prerequisites
This chapter assumes you can:
- Write Python functions, loops and list comprehensions, and use
sortedwith akeyargument. - Read Big-O notation and know that sorting costs O(n log n).
- Follow a short argument by contradiction. Later chapters use induction and contradiction heavily. This chapter only needs the basic idea.
You do not need graph theory or dynamic programming experience yet. Where those come up here, they are only used for comparison.
The Core Idea: Commit and Move On
Every optimization problem asks you to pick the best solution from a large set of feasible ones. A greedy algorithm does not look at that whole set. It repeats one small step:
- Look at the remaining candidates.
- Pick the one that scores best under a fixed selection rule, for example "shortest first" or "cheapest first".
- If adding it keeps the partial solution valid, keep it. Otherwise discard it.
- Never undo a decision.
The last point is what makes an algorithm greedy. It does not backtrack, does not keep alternatives open, and does not compare several partial solutions. That is why greedy algorithms are fast and simple to code. It is also why they are often wrong, since a choice that looks good now can rule out a better overall answer.
The Four Parts of a Greedy Algorithm
When you design or read a greedy algorithm, identify these parts:
| Part | Question it answers | Example (tasks under a time budget) |
|---|---|---|
| Candidate set | What can be added to the solution? | Individual tasks with durations |
| Selection rule | Which candidate do we try next? | Shortest duration first |
| Feasibility check | Is the partial solution still valid? | Total time stays within the budget |
| Objective | What are we optimizing? | Number of tasks completed |
Most of the design work goes into the selection rule. The other three parts usually come straight from the problem statement. There are often several plausible rules, and many of them give wrong answers.
A Worked Example: Most Tasks in a Time Budget
Suppose you have a list of task durations in hours and a budget of 8 hours. You want to finish as many tasks as possible, and it does not matter which ones. Here is a greedy solution with "shortest first" as the selection rule:
def max_tasks_greedy(durations, budget, key=lambda d: d):
chosen = []
used = 0
for d in sorted(durations, key=key):
if used + d <= budget: # feasibility check
chosen.append(d) # commit, never undo
used += d
return chosen
durations = [4, 2, 7, 1, 3]
print(max_tasks_greedy(durations, 8)) # [1, 2, 3]
print(max_tasks_greedy(durations, 8, key=lambda d: -d)) # [7, 1]The first call sorts the tasks as 1, 2, 3, 4, 7. It takes 1, 2 and 3 for a total of 6 hours. Then it rejects 4, because 10 is over the budget, and rejects 7. That gives three tasks.
The second call keeps the same loop but uses "longest first". It takes 7, rejects 4, 3 and 2, and then fits 1. That gives only two tasks. The structure of the algorithm did not change. Only the rule did, and the result got worse. A greedy algorithm is only as good as its selection rule.
Checking Against Exhaustive Search
To check whether three is really the best possible, compare against exhaustive search, which tries every subset of tasks:
from itertools import combinations
def max_tasks_brute(durations, budget):
for k in range(len(durations), -1, -1):
for combo in combinations(durations, k):
if sum(combo) <= budget:
return list(combo)
return []
print(max_tasks_brute([4, 2, 7, 1, 3], 8)) # [4, 2, 1]Exhaustive search finds [4, 2, 1], which is also three tasks. This is a different set from the greedy answer, but it has the same objective value. Optimal solutions are often not unique. A greedy algorithm only has to reach an optimal value, not a particular optimal set. Keep this in mind when you write tests. Compare objective values, not the exact solutions.
Why Shortest First Works Here
Here is an informal argument. Suppose some optimal solution has k tasks. The k shortest tasks have a total duration no larger than any other k tasks, so they also fit in the budget. Greedy takes the shortest tasks in order until the next one does not fit, so it takes at least k tasks. Later chapters turn this kind of reasoning into two formal techniques, greedy-stays-ahead and the exchange argument.
Cost: Why Greedy Is Attractive
| Approach | Explores | Typical cost here | Guarantees optimal? |
|---|---|---|---|
| Exhaustive search | Every subset | O(2^n · n) | Yes |
| Dynamic programming | Every subproblem, keeps the best of each | Polynomial in n and often the budget | Yes, if subproblems are defined correctly |
| Greedy | One path, chosen by a rule | O(n log n), dominated by the sort | Only if the problem has the right structure |
With 40 tasks, exhaustive search checks about a trillion subsets. Greedy sorts 40 numbers. Most greedy algorithms follow this pattern: one sort or a priority queue, then a linear pass.
Greedy Versus Dynamic Programming
Greedy and dynamic programming (DP) both build an optimal solution from smaller pieces. They differ in how many options they keep open.
- DP considers every choice at each step. It solves the subproblem each choice leaves behind and then takes the best combination. It decides after seeing the consequences.
- Greedy makes one choice, which the rule fixes in advance, and then solves the single subproblem that remains. It decides before seeing the consequences.
So greedy is a special case of the same recursive structure. It can skip the comparison only because, for the right problems, one choice is provably always safe. The next two chapters name these conditions: the greedy choice property (some optimal solution includes the greedy choice) and optimal substructure (an optimal solution contains optimal solutions to its subproblems).
Common Mistakes
- Rule tied to the wrong quantity. If you change our example to maximize total hours used rather than task count, shortest first stops being optimal. That version is the subset-sum problem. A small change to the objective can break a greedy rule.
- Assuming rejection is final when it should not be. In our loop, a task rejected once would be rejected forever, because
usedonly grows. If feasibility can change later, so that a rejected candidate could become valid again, the simple one-pass loop may be incorrect. - Comparing exact outputs in tests. As shown above, two correct algorithms can return different optimal sets.
- Unstable tie handling. When candidates tie under the rule, make sure the proof does not depend on which one is taken. If it does, encode the tie-break in the sort key.
Exercise
In the task-budget problem, the rule "take tasks in their original list order" is also greedy. Give a duration list and budget where it finishes fewer tasks than shortest first.
Show answer
Durations [7, 1, 1, 1] with budget 8. Original order takes 7, then one 1, then cannot fit more: 2 tasks. Shortest first takes 1, 1, 1 (total 3) and then rejects 7: 3 tasks.
Exercise
Change the objective to "maximize total hours used without exceeding the budget." Show that shortest first is no longer optimal using durations [4, 2, 7, 1, 3] and budget 8.
Show answer
Shortest first takes 1, 2, 3 for 6 hours. The subset [7, 1] or [4, 3, 1] uses exactly 8 hours, which is better. The greedy rule fit the count objective but not the total-time objective.
Exercise
Write a test harness that runs maxtasksgreedy and maxtasksbrute on 1000 random lists of 6 durations between 1 and 10, with random budgets between 1 and 30, and reports any input where the number of tasks differs. What do you expect it to print?
Show answer
For example: import random; for in range(1000): d = [random.randint(1, 10) for in range(6)]; b = random.randint(1, 30); g = len(maxtasksgreedy(d, b)); x = len(maxtasksbrute(d, b)); then if g != x: print(d, b, g, x). It should print nothing, because shortest first is optimal for maximizing the count.