Greedy Algorithms: Classic Problems
This lesson applies the greedy strategy to a series of classic problems. For some of them, a good heuristic gives the optimal solution, and we will see why. For others, it gives only a good solution, and a counterexample shows it. Learning to tell both situations apart is the main goal. The implementations are in the course repository.
- Two disk problems that look alike, but where the same idea is optimal in one case and not in the other.
- The knapsack problem: three heuristics, the optimal one for fractional objects, and why it fails when objects cannot be broken.
- The diligent plumber: minimizing the waiting time with one or several workers, and an exchange argument that proves optimality.
- The knight's tour, where a smart heuristic makes all the difference.
- The assignment of tasks to agents and graph coloring, two problems where greedy algorithms give good but not always optimal solutions.
- Some famous greedy algorithms that are always optimal.
Files on a Disk
Maximize the number of files
We have a disk with a capacity of 880 MB and want to store as many files as possible from a list with these sizes (in MB): 100, 350, 450, 370, 5000, 500, 700, 800, 50.
Heuristic: store the smallest files first, while there is enough space.
Sorted: 50, 100, 350, 370 | 450, 500, 700, 800, 5000. The first four files occupy MB; the next one, 450 MB, does not fit, and neither will any larger one. Result: 4 files.
public int maximizeFileCount(int[] files, int diskCapacity) {
int[] sorted = files.clone();
Arrays.sort(sorted); // O(n log n)
int usedSpace = 0, fileCount = 0;
for (int size : sorted) {
if (usedSpace + size > diskCapacity) break; // no larger file will fit either
usedSpace += size;
fileCount++;
}
return fileCount;
}
This heuristic is optimal. Exchange argument: take any optimal selection of files. If it contains a file that is larger than some file left out, exchanging them keeps files and does not increase the space used. Repeating the exchange, we reach the smallest files, which therefore also fit. So the greedy algorithm, which takes as many of the smallest files as fit, stores at least files.
ProofFiles on a disk: smallest files firstMinimize the free space
Now the disk has 1200 MB, and we want to fill it as much as possible (minimize the free space) with the same files.
Heuristic: store the largest files first, while they fit.
The 5000 MB file does not fit; 800 fits (800 used); 700 does not; 500 does not; 450 does not; 370 fits (1170 used); 350, 100 and 50 no longer fit. Result: 1170 MB, with 30 MB free.
But : the disk can be filled completely. The heuristic is not optimal, and this input is a counterexample. In fact, this problem (known as the subset sum problem) is computationally hard: no efficient algorithm that always finds the optimum is known. Greedy algorithms only give an approximation; exact solutions need techniques such as dynamic programming or backtracking.
Both problems use the same strategy (sort, then take while it fits), and the code is almost identical. But "smallest first" is provably optimal for counting files, while "largest first" is just a reasonable heuristic for filling space. Always ask whether the heuristic matches the objective.
The Knapsack Problem
We have objects and a backpack. Each object has a weight and a value , and the backpack can carry a total weight not exceeding . The goal is to maximize the total value of the objects carried, respecting the weight limit.
In the fractional version, objects can be broken: we can carry a fraction of object , with (think of gold dust, or liquids). The problem is:
With the greedy elements: the candidates are the objects; the state is the solution vector ; the feasibility condition is ; and the selection function is the heuristic.
Data
Five objects and a weight limit :
| Object | 1 | 2 | 3 | 4 | 5 |
|---|---|---|---|---|---|
| Weight | 10 | 20 | 30 | 40 | 50 |
| Value | 20 | 30 | 66 | 40 | 60 |
| Value per weight unit | 2 | 1.5 | 2.2 | 1 | 1.2 |
Three heuristics
- Most valuable first
- Lightest first
- Best value per weight first
Take objects in decreasing value: 3 (66), 5 (60), 4 (40)...
- Object 3: weight 30, value 66 (total weight 30).
- Object 5: weight 50, value 60 (total weight 80).
- Object 4: only 20 of its 40 units fit: half of it, value 20 (total weight 100).
: total value 146.
Take objects in increasing weight: 1, 2, 3, 4...
- Objects 1, 2, 3 and 4: weights , values .
- Object 5 does not fit at all.
: total value 156.
Take objects in decreasing value per weight unit: 3 (2.2), 1 (2), 2 (1.5), 5 (1.2), 4 (1).
- Objects 3, 1 and 2: weights , values .
- Object 5: 40 of its 50 units fit: , value .
: total value 164.
The data is a counterexample showing that the first two heuristics are not optimal. The third one, the best value per weight unit, is optimal for the fractional knapsack. Intuition (exchange argument): if an optimal solution carried some weight of an object with a lower ratio while leaving out part of an object with a higher ratio, replacing that weight with the better object would increase the value. So the best solution uses the highest ratios first, as the greedy algorithm does.
public float[] fillKnapsack(int maxWeight, int[] weights, int[] values) {
// sort the objects by decreasing value/weight (O(n log n))
...
int currentWeight = 0;
for (Item item : items) {
if (currentWeight == maxWeight) break; // the knapsack is full
if (currentWeight + item.weight <= maxWeight) {
solution[item.index] = 1.0f; // take the whole object
currentWeight += item.weight;
} else {
solution[item.index] = (float) (maxWeight - currentWeight) / item.weight; // a fraction
currentWeight = maxWeight;
}
}
return solution;
}
The cost is dominated by sorting: .
ProofThe fractional knapsack: highest value per weight firstWithout breaking objects: the 0/1 knapsack
If objects cannot be broken (), the greedy algorithm is no longer optimal, even with the best heuristic. Counterexample with :
| Object | 1 | 2 | 3 |
|---|---|---|---|
| Weight | 5 | 3 | 3 |
| Value | 11 | 6 | 6 |
| 2.2 | 2 | 2 |
The greedy algorithm takes object 1 (the best ratio, value 11), and then nothing else fits: total value 11. The optimal solution takes objects 2 and 3, with a worse ratio, but a total value of 12.
To adapt the algorithm to indivisible objects, the selection function must skip the objects that no longer fit, and the loop must stop when no remaining object fits (for example, when the selection returns ). But even then, the result is only an approximation. The 0/1 knapsack problem is solved optimally with dynamic programming, backtracking or branch and bound, which you will study in the following chapters.
The Diligent Plumber
A plumber needs to make urgent repairs, and he knows in advance how long each one will take: minutes for the -th task. He wants to minimize the average waiting time of his customers (to keep them as happy as possible). If is the time that the -th customer waits until his repair is finished, he must minimize:
The plumber always needs the same total time to finish all the tasks, , whatever the order. But the waiting times depend on the order: if the tasks are done in the order , then
The problem is to find the order (permutation) of the tasks that minimizes .
Heuristic: do the shortest tasks first (the shortest processing time rule).
🧠 Checkpoint: Compute the minimum waiting time
Question: The tasks take 7, 5, 4, 3, 6, 8 and 2 minutes. What is the minimum total waiting time?
Answer: Sorted: 2, 3, 4, 5, 6, 7, 8. The waiting times are the cumulative sums: 2, 5, 9, 14, 20, 27, 35, whose total is 112 minutes. For comparison, doing the tasks in the given order (7, 5, 4, 3, 6, 8, 2) gives 147, and the worst order (longest first) gives 168.
Why is it optimal? An exchange argument
Each task delays every task done after it. If the tasks are done in the order :
The first task is counted times, the last one only once. Now take any order in which a longer task is done immediately before a shorter task (). Exchanging them changes only their two waiting times: before, the task in the earlier of the two positions was the long one, and it delayed the other; after the exchange, the short one goes first. The total waiting time decreases by exactly . So any order that is not sorted can be improved, and the sorted order is optimal. The cost is that of sorting: .
ProofThe plumber: shortest tasks firstSeveral plumbers
The company hires more plumbers: now there are plumbers for the tasks, and the goal is still to minimize the total waiting time. The greedy strategy becomes:
- Sort the tasks by increasing duration, as before.
- Assign the tasks in that order, each one to the least busy plumber.
With 3 plumbers and the same tasks (7, 5, 4, 3, 6, 8, 2), sorted as 2, 3, 4, 5, 6, 7, 8:
| Plumber | Tasks | Waiting times of his customers |
|---|---|---|
| A | 2, 5, 8 | 2, 7, 15 |
| B | 3, 6 | 3, 9 |
| C | 4, 7 | 4, 11 |
Total waiting time: 51 minutes. Since the tasks are sorted, assigning them to the least busy plumber is the same as distributing them in turns (task 1 to A, task 2 to B, task 3 to C, task 4 to A...), which is how the course implementation does it. This strategy is also optimal.
The Knight's Tour
The problem consists of traversing the entire chessboard with a knight, visiting each square exactly once, using the knight's L-shaped moves (two squares in one direction and one in the perpendicular direction). From a square in the center of the board, a knight can reach 8 squares; near the edges and corners, fewer.
A greedy algorithm builds the tour step by step, choosing the next square with a heuristic, and never goes back. Two heuristics:
- A simple one: go to the first available square, in a fixed order of the 8 possible moves.
- A more effective one: go to the square from which there are fewer possible onward jumps. This is Warnsdorff's rule (1823). The idea is to visit first the squares that are hard to reach (corners and edges), before they become isolated.
private int findBestNextMove(int x, int y) {
int minOnwardJumps = Integer.MAX_VALUE;
int bestMove = -1;
for (int i = 0; i < 8; i++) { // the 8 knight moves
int nx = x + DX[i], ny = y + DY[i];
if (isValidSquare(nx, ny)) { // inside the board and not visited
int onward = countOnwardJumps(nx, ny);
if (onward < minOnwardJumps) {
minOnwardJumps = onward;
bestMove = i;
}
}
}
return bestMove; // -1 if the knight is stuck
}
We ran both heuristics of the course repository on an board, starting from each of the 64 squares:
| Heuristic | Complete tours found |
|---|---|
| First available square | 0 of 64 |
| Fewest onward jumps (Warnsdorff) | 63 of 64 |
The simple heuristic always gets stuck before visiting every square. Warnsdorff's rule succeeds almost always, with an algorithm for an board. But not always: from one of the starting squares, with the order in which the course implementation breaks ties, it also gets stuck, although a tour exists from every square. A greedy algorithm cannot guarantee a solution here; backtracking, which can undo bad decisions, can (at a much higher cost).
Assigning Tasks to Agents
We must assign tasks to agents, so that each agent performs exactly one task. We know the cost of performing task by agent , in a cost matrix:
| Agent \ Task | 1 | 2 | … | n |
|---|---|---|---|---|
| a | 11 | 12 | … | 40 |
| b | 14 | 15 | … | 22 |
| … | ||||
| n | 17 | 14 | … | 28 |
Goal: minimize the total cost of executing the tasks.
Two natural greedy heuristics:
- By rows: take the agents in order, and assign to each one the least expensive task that is still available.
- By columns: take the tasks in order, and assign each one to the agent for whom it is least expensive, among those still available.
Both are fast, , since each assignment scans a row or a column. Are they optimal? Try a few small matrices by hand: you will find out whether choosing the cheapest option for the first agents can force the last ones into very expensive tasks. We will come back to this problem in the backtracking and branch and bound chapters, which find the optimal assignment. (In lab session 4 you will work on a variant of this problem.)
Graph Coloring
In graph theory, graph coloring is a special case of graph labelling:
- vertex coloring paints the vertices of a graph so that no two adjacent vertices share the same color;
- edge coloring paints the edges so that no two adjacent edges (with a common endpoint) share the same color.
The goal is to use as few colors as possible. The minimum number of colors needed for the vertices is the chromatic number of the graph.
A greedy algorithm
Color the first node with the first color
For each of the remaining n - 1 nodes:
color it with the lowest-numbered color that has not been used
on any previously colored node adjacent to it
(if all the colors used so far appear on adjacent nodes, use a new color)
It is fast: with an adjacency matrix. But the number of colors depends heavily on the order in which the nodes are visited. We tested it on a "crown" graph with 8 nodes ( and , where each is connected to every with ). This graph can be colored with just 2 colors (all the nodes with one color and all the nodes with another), and the greedy algorithm finds that coloring if it visits the nodes in the order But in the order it uses 4 colors. For larger crown graphs, the gap grows without limit.
So the greedy algorithm does not always find the chromatic number. In fact, computing the chromatic number of a general graph is a computationally hard problem. Better orders (for example, visiting first the nodes with more neighbours) usually help, but guarantee nothing.
Applications
Graph coloring models many practical problems in which some things cannot share a resource:
- making schedules and timetables: exams that share students cannot be scheduled at the same time (each color is a time slot);
- assigning radio frequencies to mobile phone antennas that interfere with each other;
- Sudoku: each cell is a node, cells in the same row, column or box are adjacent, and the 9 digits are the colors;
- map coloring: neighbouring countries must have different colors.
Any map drawn on a plane can be colored with at most four colors so that neighbouring regions have different colors. This was conjectured in 1852 and proved only in 1976 by Kenneth Appel and Wolfgang Haken, with a proof that required checking a large number of cases by computer, the first major theorem proved this way.
Minimum Spanning Trees: Prim and Kruskal
Problem. A company wants to connect offices with a network. The cost of a direct cable between each pair of offices is known. Which cables should be installed so that all the offices are connected, directly or indirectly, at the minimum total cost? In graph terms: given a connected undirected graph with weights on its edges, find a minimum spanning tree, a set of edges that connects all the nodes, has no cycles (a cycle would contain a useless cable), and has the minimum total weight. A spanning tree of nodes always has exactly edges.
Two classic greedy algorithms solve it, and both are always optimal.
We use this graph of six nodes, with the weight of each edge on it:
Prim's algorithm
Prim's algorithm grows a single tree from a starting node. At each step it adds the cheapest edge that connects the tree with a node outside it. Starting from node 1:
| Step | Nodes in the tree | Cheapest edge leaving the tree | Total |
|---|---|---|---|
| 1 | 1 | 1-3 (1) | 1 |
| 2 | 1, 3 | 3-6 (4) | 5 |
| 3 | 1, 3, 6 | 6-4 (2) | 7 |
| 4 | 1, 3, 4, 6 | 3-2 (5) | 12 |
| 5 | 1, 2, 3, 4, 6 | 2-5 (3) | 15 |
The tree has the edges 1-3, 3-6, 6-4, 3-2 and 2-5, with total weight 15. In step 4 there are three candidates of weight 5 (1-4, 3-2 and 3-4); 1-4 and 3-4 would join two nodes already in the tree (forming a cycle), so they are not candidates at all, and 3-2 is the only edge of weight 5 that reaches a new node.
An implementation with an adjacency matrix keeps, for every node outside the tree, the weight dist[v] of its cheapest edge to the tree:
static final int INF = Integer.MAX_VALUE;
int prim(int[][] w) { // w[u][v] = 0 if there is no edge
int n = w.length;
boolean[] inTree = new boolean[n];
int[] dist = new int[n]; // cheapest edge from v to the tree
Arrays.fill(dist, INF);
dist[0] = 0; // start at node 0
int total = 0;
for (int step = 0; step < n; step++) {
int u = -1; // greedy choice: the closest node outside the tree
for (int v = 0; v < n; v++)
if (!inTree[v] && dist[v] != INF && (u == -1 || dist[v] < dist[u]))
u = v;
inTree[u] = true;
total += dist[u];
for (int v = 0; v < n; v++) // update the candidates
if (!inTree[v] && w[u][v] > 0 && w[u][v] < dist[v])
dist[v] = w[u][v];
}
return total;
}
Each of the steps scans the nodes twice: , which is optimal for dense graphs given as a matrix. With adjacency lists and a priority queue, it costs for edges, better for sparse graphs.
Kruskal's algorithm
Kruskal's algorithm looks at the edges in increasing order of weight, and accepts each one unless it would form a cycle with the edges already accepted. At the beginning every node is a separate tree; each accepted edge joins two trees into one.
| Edge (weight) | Decision |
|---|---|
| 1-3 (1) | accept |
| 4-6 (2) | accept |
| 2-5 (3) | accept |
| 3-6 (4) | accept: joins the trees of 1-3 and 4-6 |
| 1-4 (5) | reject: 1 and 4 are already connected (1-3-6-4) |
| 2-3 (5) | accept: joins the tree of 2-5 with the rest. Five edges: stop |
The result is a different tree (1-3, 4-6, 2-5, 3-6, 2-3) with the same total weight, 15: when several edges have the same weight, there may be several minimum spanning trees. To check quickly whether an edge forms a cycle, Kruskal's algorithm uses a union-find (disjoint sets) structure, which keeps the current trees as sets: an edge is rejected if both ends are in the same set. Sorting the edges dominates the cost: .
Why are they optimal? Both rely on the same property: for any division of the nodes into two groups, the cheapest edge that crosses between the groups belongs to some minimum spanning tree. Prim applies it to the division "tree / rest"; Kruskal, to the two trees that the accepted edge joins.
ProofPrim and Kruskal are optimalGreedy Algorithms That Are Always Optimal
For some important problems, a well-chosen greedy algorithm is provably optimal. You will meet several of them in your degree:
- Dijkstra's algorithm (Dijkstra, 1959) finds the shortest paths from one node to all the others in a graph with non-negative weights, by repeatedly fixing the closest node not yet fixed.
- Prim's algorithm and Kruskal's algorithm find a minimum spanning tree, as seen in the previous section.
- Huffman coding (Huffman, 1952) builds an optimal prefix code for data compression, by repeatedly merging the two least frequent symbols.
- Interval scheduling: to attend the maximum number of non-overlapping activities, repeatedly choose the one that finishes first.
- Solving the 0/1 knapsack greedily by value/weight. It is optimal only for the fractional knapsack.
- Sorting by the wrong criterion. By value alone or by weight alone fails even in the fractional knapsack.
- Taking the colors of the greedy coloring as the minimum. The result depends on the order of the nodes.
- Adding an edge that closes a cycle in Kruskal's algorithm. Check it with a union-find structure.
Summary
| Problem | Heuristic | Optimal? |
|---|---|---|
| Change (canonical coins, unlimited) | Highest coin that fits | Yes |
| Change (any coins) | Highest coin that fits | No |
| Maximize the number of files | Smallest files first | Yes |
| Minimize free space on a disk | Largest files first | No |
| Fractional knapsack | Highest value per weight first | Yes |
| 0/1 knapsack | Highest value per weight first | No |
| One or several plumbers | Shortest tasks first | Yes |
| Knight's tour | Fewest onward jumps (Warnsdorff) | Usually finds a tour; not guaranteed |
| Tasks to agents | Cheapest per row or per column | Think about it (see the exercises) |
| Graph coloring | Lowest available color | No |
Practice
- 💾 Disks. Find the optimal way of filling a disk of 1500 MB with the files of this lesson, and compare it with the greedy result.
- 🎒 Knapsack. Run the fractional knapsack of the repository with the data of this lesson. Then design an input for which "lightest first" gives a worse result than "most valuable first".
- 🔧 Plumbers. Prove that, with one plumber, the total waiting time for the order is . Compute it for the tasks 9, 1, 4, 6 in the best and the worst order.
- ♞ Knight's tour. Run both versions of the knight's tour on boards of size 5 to 12. For which sizes does Warnsdorff's rule find a tour from the corner?
- 👥 Agents. Build a cost matrix for which the "by rows" heuristic does not give the cheapest assignment.
- 🎨 Coloring. Color the graph of the countries of South America with the greedy algorithm, visiting the countries in alphabetical order. How many colors do you need? Can you do it with fewer by changing the order?
Errors, suggestions and public questions open a form on GitHub, visible to everyone.