Skip to main content

Greedy Algorithms: Classic Problems

21 min readRead first: The Greedy Method · Data Structures

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.

What you will learn in this lesson
  • 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 50+100+350+370=87050 + 100 + 350 + 370 = 870 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 kk files. If it contains a file that is larger than some file left out, exchanging them keeps kk files and does not increase the space used. Repeating the exchange, we reach the kk smallest files, which therefore also fit. So the greedy algorithm, which takes as many of the smallest files as fit, stores at least kk files.

ProofFiles on a disk: smallest files first

Minimize 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 800+350+50=1200800 + 350 + 50 = 1200: 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.

The same idea, two different results

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 nn objects and a backpack. Each object ii has a weight wiw_i and a value viv_i, and the backpack can carry a total weight not exceeding WW. 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 xix_i of object ii, with 0≤xi≤10 \le x_i \le 1 (think of gold dust, or liquids). The problem is:

maximize ∑i=1nxivisubject to∑i=1nxiwi≤W,0≤xi≤1\text{maximize } \sum_{i=1}^{n} x_i v_i \quad \text{subject to} \quad \sum_{i=1}^{n} x_i w_i \le W, \quad 0 \le x_i \le 1

With the greedy elements: the candidates are the nn objects; the state is the solution vector X=(x1,x2,…,xn)X = (x_1, x_2, \dots, x_n); the feasibility condition is ∑xiwi≤W\sum x_i w_i \le W; and the selection function is the heuristic.

Data​

Five objects and a weight limit W=100W = 100:

Object12345
Weight wiw_i1020304050
Value viv_i2030664060
Value per weight unit vi/wiv_i / w_i21.52.211.2

Three heuristics​

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).

x=(0,0,1,0.5,1)x = (0, 0, 1, 0.5, 1): total value 146.

The fractional knapsack with capacity 100 filled by three heuristicscapacity W = 100most valuable first350.5·4value 146lightest first1234value 156best value per weight3120.8·5value 164block width = weight carried · 0.5·4 = half of object 4 · objects: 1 (10, 20), 2 (20, 30), 3 (30, 66), 4 (40, 40), 5 (50, 60)
The three heuristics on the same data. Each block is an object, as wide as the weight carried; all three fill the capacity of 100, but only the best value per weight reaches the optimum, 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: O(nlog⁡n)O(n \log n).

ProofThe fractional knapsack: highest value per weight first

Without breaking objects: the 0/1 knapsack​

If objects cannot be broken (xi∈{0,1}x_i \in \{0, 1\}), the greedy algorithm is no longer optimal, even with the best heuristic. Counterexample with W=6W = 6:

Object123
Weight wiw_i533
Value viv_i1166
vi/wiv_i / w_i2.222

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 −1-1). 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 nn urgent repairs, and he knows in advance how long each one will take: tit_i minutes for the ii-th task. He wants to minimize the average waiting time of his customers (to keep them as happy as possible). If wiw_i is the time that the ii-th customer waits until his repair is finished, he must minimize:

W(n)=∑i=1nwiW(n) = \sum_{i=1}^{n} w_i

The plumber always needs the same total time to finish all the tasks, T=t1+t2+⋯+tnT = t_1 + t_2 + \cdots + t_n, whatever the order. But the waiting times depend on the order: if the tasks are done in the order 1,2,…,n1, 2, \dots, n, then

w1=t1,w2=t1+t2,…,wn=t1+t2+⋯+tnw_1 = t_1, \quad w_2 = t_1 + t_2, \quad \dots, \quad w_n = t_1 + t_2 + \cdots + t_n

The problem is to find the order (permutation) of the tasks that minimizes W(n)W(n).

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.

The plumber: the same total time, but doing the shortest tasks first reduces the total waiting time from 147 to 112given order77512416319625833235Σ waits = 147shortest first223549514620727835Σ waits = 112small numbers: the moment each customer is served; their sum is the total waiting time
The tasks of the checkpoint in the given order and sorted. The total time is 35 in both cases, but each customer waits until his task ends: shortest first, the waits add up to 112 instead of 147.

Why is it optimal? An exchange argument​

Each task delays every task done after it. If the tasks are done in the order t1,t2,…,tnt_1, t_2, \dots, t_n:

W(n)=n⋅t1+(n−1)⋅t2+⋯+1⋅tnW(n) = n \cdot t_1 + (n-1) \cdot t_2 + \cdots + 1 \cdot t_n

The first task is counted nn times, the last one only once. Now take any order in which a longer task aa is done immediately before a shorter task bb (a>ba \gt b). 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 a−b>0a - b \gt 0. So any order that is not sorted can be improved, and the sorted order is optimal. The cost is that of sorting: O(nlog⁡n)O(n \log n).

ProofThe plumber: shortest tasks first

Several plumbers​

The company hires more plumbers: now there are FF plumbers for the nn tasks, and the goal is still to minimize the total waiting time. The greedy strategy becomes:

  1. Sort the tasks by increasing duration, as before.
  2. 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:

PlumberTasksWaiting times of his customers
A2, 5, 82, 7, 15
B3, 63, 9
C4, 74, 11

Total waiting time: 2+7+15+3+9+4+11=2 + 7 + 15 + 3 + 9 + 4 + 11 = 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:

  1. A simple one: go to the first available square, in a fixed order of the 8 possible moves.
  2. 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 8×88 \times 8 board, starting from each of the 64 squares:

HeuristicComplete tours found
First available square0 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 O(n2)O(n^2) algorithm for an n×nn \times n 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 nn tasks to nn agents, so that each agent performs exactly one task. We know the cost of performing task jj by agent ii, in a cost matrix:

Agent \ Task12…n
a1112…40
b1415…22
…
n1714…28

Goal: minimize the total cost of executing the nn tasks.

Two natural greedy heuristics:

  1. By rows: take the agents in order, and assign to each one the least expensive task that is still available.
  2. 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, O(n2)O(n^2), 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: O(n2)O(n^2) 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 (u0,…,u3u_0, \dots, u_3 and v0,…,v3v_0, \dots, v_3, where each uiu_i is connected to every vjv_j with j≠ij \ne i). This graph can be colored with just 2 colors (all the uu nodes with one color and all the vv nodes with another), and the greedy algorithm finds that coloring if it visits the nodes in the order u0,u1,u2,u3,v0,…u_0, u_1, u_2, u_3, v_0, \dots But in the order u0,v0,u1,v1,…u_0, v_0, u_1, v_1, \dots it uses 4 colors. For larger crown graphs, the gap grows without limit.

Greedy coloring of a crown graph: 2 colors in one order, 4 colors in anotherorder u0, u1, u2, u3, v0, ...: 2 colorsu0v0u1v1u2v2u3v3all the u first: optimalorder u0, v0, u1, v1, ...: 4 colorsu0v0u1v1u2v2u3v3alternating: twice as many colors
The greedy coloring of the crown graph in two orders. Visiting all the u nodes first gives the optimal 2 colors; alternating u and v nodes forces 4.

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.
The four color theorem

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 nn 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 nn nodes always has exactly n−1n - 1 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:

A weighted graph with six nodes, used to build a minimum spanning tree with the algorithms of Prim and Kruskal6155356426123456
The example graph: six nodes and ten weighted edges.

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:

StepNodes in the treeCheapest edge leaving the treeTotal
111-3 (1)1
21, 33-6 (4)5
31, 3, 66-4 (2)7
41, 3, 4, 63-2 (5)12
51, 2, 3, 4, 62-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 nn steps scans the nn nodes twice: O(n2)O(n^2), which is optimal for dense graphs given as a matrix. With adjacency lists and a priority queue, it costs O(mlog⁡n)O(m \log n) for mm 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: O(mlog⁡m)O(m \log m).

Minimum spanning trees found by Prim (from node 1) and Kruskal on the same graph, both of total weight 1561#155#43#5564#22#36123456Prim: grow one tree from node 161#155#53#3564#42#26123456Kruskal: cheapest edges without cycles#k: order in which the edge is added · green: tree edges (total 15) · red dashed: rejected by Kruskal (would close a cycle)
The trees found by Prim (left, starting at node 1) and Kruskal (right). The numbers #1 to #5 give the order in which each edge is added. The trees differ in one edge but both weigh 15; Kruskal rejects 1-4 because nodes 1 and 4 are already connected.

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 optimal

Greedy 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.
Common mistakes
  • 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​

ProblemHeuristicOptimal?
Change (canonical coins, unlimited)Highest coin that fitsYes
Change (any coins)Highest coin that fitsNo
Maximize the number of filesSmallest files firstYes
Minimize free space on a diskLargest files firstNo
Fractional knapsackHighest value per weight firstYes
0/1 knapsackHighest value per weight firstNo
One or several plumbersShortest tasks firstYes
Knight's tourFewest onward jumps (Warnsdorff)Usually finds a tour; not guaranteed
Tasks to agentsCheapest per row or per columnThink about it (see the exercises)
Graph coloringLowest available colorNo

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 t1,…,tnt_1, \dots, t_n is ∑i=1n(n−i+1) ti\sum_{i=1}^{n} (n - i + 1)\, t_i. 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 3×33 \times 3 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?
Saved only in your browser
Was this lesson helpful?
Questions, or something wrong?

Errors, suggestions and public questions open a form on GitHub, visible to everyone.