The Greedy Method
Many problems ask not just for a solution, but for the best one: the fewest coins, the shortest route, the highest value, the smallest waiting time. These are optimization problems. Greedy algorithms attack them in the simplest possible way: they build the solution step by step and, at each step, they take the choice that looks best right now, without ever reconsidering it.
This strategy is fast and easy to implement, and for some problems it produces the optimal solution. For many others it does not. The art of greedy algorithms lies in knowing which situation we are in.
- The characteristics of greedy algorithms: local decisions, heuristics and irreversibility.
- The elements of a greedy algorithm and its general scheme.
- When a greedy algorithm is optimal, how to prove it, and how to disprove it with a counterexample.
- The problem of the change, with its conditions for optimality and a subtle implementation trap.
- Many classic examples: files on a disk, the knapsack problem, the diligent plumber, the knight's tour, assigning tasks to agents and graph coloring.
The Idea
Greedy algorithms:
- are used in optimization problems;
- like other techniques, build the solution step by step;
- at each step, look for the locally optimal choice, hoping that the sequence of local optima leads to the global optimum;
- choose using heuristic rules (rules of thumb), based on some knowledge about the problem.
Decisions are never reconsidered
A greedy algorithm makes its decisions based on the information available locally, at the moment of deciding. And a decision, once made, is never reconsidered: there is no need to keep track of past decisions or to undo them. This is what makes greedy algorithms so fast, and also what makes them fail when an early choice turns out to be a bad one.
The tree of states
The process can be seen as a path through the tree of states of the problem: a (virtual) tree whose root is the initial state, whose children are the states reachable with one decision, and so on. Exhaustive techniques, such as backtracking (which you will study later), explore many branches of that tree. A greedy algorithm develops a single path: at each node, the heuristic indicates which child to follow, and the others are discarded forever.
For this to work, every state that is developed must be achievable: from it, it must still be possible to reach a solution of the problem.
Key Features
The main features of greedy algorithms are:
- They are quick and easy to implement: usually a loop that selects, checks and adds, often after sorting the candidates.
- They depend entirely on the quality of the heuristic. A low-quality heuristic may not provide optimal solutions; in the worst case, it might not provide a solution at all, even though the problem has one.
So they are appropriate when:
- the heuristic is good enough to guarantee the optimal solution (and we can prove it), or
- there is no time to apply other techniques, and a good (not necessarily optimal) solution found quickly is valuable. In this case, the greedy algorithm acts as a heuristic method, or as a fast way to obtain an initial solution for other techniques.
Many problems cannot be solved optimally with this approach. For them, we will need the techniques of the following chapters: dynamic programming, backtracking and branch and bound.
Elements of a Greedy Algorithm
Most greedy algorithms can be described with the same elements:
- a set of candidates (coins, objects, tasks, edges...);
- the partial solution built so far (the candidates already chosen);
- a selection function (the heuristic) that chooses the most promising candidate at each step;
- a feasibility function that checks whether adding a candidate to the partial solution keeps it valid (for example, without exceeding a capacity);
- a solution function that checks whether the partial solution is already a complete solution;
- an objective function that gives the value of a solution, which we want to minimize or maximize.
General outline
void greedy(State currentState) {
while (!isSolution()) {
if (currentState.meetsHeuristic())
currentState = selectedState; // accept the selected choice
else
currentState = currentState.nextState(); // discard it and try the next one
}
}
In more detail, with the elements above:
Solution greedy(Set<Candidate> candidates) {
Solution solution = empty;
while (!candidates.isEmpty() && !isSolution(solution)) {
Candidate x = select(candidates); // the heuristic: the most promising one
candidates.remove(x); // never considered again
if (isFeasible(solution, x))
solution.add(x); // decisions are never undone
}
return isSolution(solution) ? solution : NO_SOLUTION;
}
When the selection function consists of taking the candidates in a fixed order (by size, by value, by ratio...), the algorithm usually starts by sorting the candidates, and its complexity is dominated by that sorting: .
The Problem of the Change
Problem. Design an algorithm to pay a certain amount of money using the fewest possible coins.
For example, to pay €2.89 with euro coins (€2, €1, 50, 20, 10, 5, 2 and 1 cents), a cashier would naturally give: one €2 coin, one 50-cent coin, one 20-cent coin, one 10-cent coin, one 5-cent coin and two 2-cent coins. Seven coins, which is optimal.
Heuristic: take the coin of the highest value that does not exceed the amount that remains to be paid.
int[] calculateCoins(int amount, int[] coins) { // amount in cents, coins in decreasing order
int[] solution = new int[coins.length];
int remaining = amount;
for (int i = 0; i < coins.length && remaining > 0; i++) {
solution[i] = remaining / coins[i]; // as many coins of this value as possible
remaining = remaining % coins[i]; // what is left to pay
}
return solution; // if remaining > 0, there was no solution
}
Taking as many coins as possible of each value at once (with a division and a remainder) is equivalent to taking them one by one, but faster. The complexity is , where is the number of different coins.
A counterexample
Depending on the monetary system and on the availability of coins, this heuristic does not always provide the optimal solution. To prove that a greedy algorithm is not optimal, a single counterexample is enough:
- We need to pay €0.60.
- Available coins: €0.50, €0.20, €0.02.
- Greedy solution: €0.50 + 5 × €0.02 = 6 coins.
- Optimal solution: 3 × €0.20 = 3 coins.
The first choice (the 50-cent coin) looked best, but it led to a bad solution, and a greedy algorithm never goes back. This problem can be solved optimally with other techniques: backtracking, which explores all the possibilities, or dynamic programming, which is the usual choice for it.
🧠 Checkpoint: Can greedy even fail to find a solution?
Question: With coins of €0.50 and €0.20 only, how does the greedy algorithm pay €0.60?
Answer: It takes a 50-cent coin, and then cannot pay the remaining 10 cents with the available coins: it reports no solution. But a solution exists: 3 × €0.20. This illustrates the warning above: a poor heuristic may fail to find a solution even when the problem has one.
When is the greedy change optimal?
With the previous heuristic, the solution is always optimal if two conditions hold:
- the monetary system is composed of coins with values , where and (for example, 1, 2, 4, 8, 16... or 1, 10, 100...);
- we have an unlimited number of coins of each value.
This can be proved (the proof is linked at the end of this section). These conditions are sufficient, but not necessary: many real systems, like the euro (1, 2, 5, 10, 20, 50, 100, 200 cents) or the US dollar, are not of this form, but they are designed so that the greedy algorithm is still optimal (they are called canonical coin systems). The system 50, 20, 2 of the counterexample is not canonical.
double for moneyThe pseudocode of this problem is often written with the amount as a real number (double amount = 2.89). But real numbers are stored in binary and most decimal amounts cannot be represented exactly. We tried it with the euro coins written as double values (2, 1, 0.5, 0.2...):
- to pay €0.30, the algorithm returned 0.20 + 0.05 + 0.02 + 0.02, a total of €0.29: after subtracting, the remainder was 0.0099999... instead of 0.01, so the 1-cent coin "did not fit";
- for €2.89 it returned the right coins, but with a remainder of instead of 0.
Always represent money with integers (cents), as in the code above, or with BigDecimal.
How to Know if a Greedy Algorithm Is Optimal
Since greedy algorithms are so easy to write, the real question is always: is the result optimal?
Disproving: find a counterexample
A single input for which the greedy result is worse than the best possible one proves that the heuristic is not optimal. Small inputs, solved by hand or by brute force, are the best source of counterexamples. A stress test (as in the first chapter) comparing the greedy algorithm with an exhaustive search on many small random inputs finds them automatically.
Proving: two properties
For a greedy algorithm to be optimal, the problem usually needs two properties:
- The greedy choice property: there is always an optimal solution that contains the choice made by the heuristic. Making that choice never closes the door to the optimum.
- Optimal substructure: after making the choice, what remains is a smaller problem of the same kind, and an optimal solution of it, combined with the choice, gives an optimal solution of the whole problem.
The most common way to prove the greedy choice property is an exchange argument: take any optimal solution that does not follow the greedy rule, and show that exchanging some of its elements so that it follows the rule does not make it worse. You will see an example of this argument with the diligent plumber in the next lesson.
A Curiosity: Egyptian Fractions
The ancient Egyptians wrote fractions as sums of distinct unit fractions (fractions with numerator 1). For example, to divide 5 loaves of bread among 8 people, : give each person half a loaf and an eighth of a loaf.
Every fraction can be written this way, and Fibonacci (the same Leonardo of Pisa of the rabbits) described a greedy algorithm to do it: subtract the largest unit fraction that fits, and repeat with what remains. For , the largest unit fraction that fits is (since ). The numerator of the remainder always decreases, so the algorithm always terminates, with at most as many terms as the original numerator.
But the result can be far from the best one. Applying the greedy algorithm to we obtained:
while there are decompositions with only three terms and much smaller denominators. Whether every fraction can be written with just three unit fractions is the Erdős–Straus conjecture (1948), which is still unproven. The short film The Mystery of Egyptian Fractions tells this story.
- Assuming a greedy algorithm is optimal because it works on some examples. Optimality needs a proof; a single counterexample disproves it.
- Reconsidering decisions. Then it is no longer a greedy algorithm, and its cost changes.
- Assuming the greedy change works for any coin system. It is optimal for canonical systems, such as the euro, not in general.
Summary
- Greedy algorithms solve optimization problems by building the solution step by step, taking the locally best choice according to a heuristic, and never reconsidering a decision.
- They are fast and simple, but their results depend entirely on the heuristic: they may be optimal, merely good, or even fail to find a solution.
- Their elements are the candidates, the selection function, the feasibility function, the solution function and the objective function.
- A single counterexample proves that a greedy algorithm is not optimal. Proving optimality requires the greedy choice property and optimal substructure, usually through an exchange argument.
- The greedy change is optimal for coin systems with unlimited coins (and for canonical systems like the euro), but not in general. Never represent money with floating-point numbers.
Practice
- 💰 Change. Run the course implementation with euro coins for several amounts. Then find, for the coin system 1, 3, 4, an amount for which the greedy algorithm is not optimal.
- 🐞 The floating-point trap. Implement the change algorithm with
doublevalues, and write a loop that checks every amount from €0.01 to €5.00. For how many amounts is the result wrong? - 🔍 Stress test. Write a brute-force (or dynamic programming) solution for the change problem, and compare it with the greedy one on all amounts up to 100 for random coin systems. How often is the greedy algorithm optimal?
- 🏺 Egyptian fractions. Implement Fibonacci's greedy algorithm with
BigIntegerand decompose . How many digits has the largest denominator?
Errors, suggestions and public questions open a form on GitHub, visible to everyone.