Greedy Algorithm Foundations
A greedy rule is only as good as its proof. This lesson takes one scheduling problem, tries three sorting rules on it, and uses an exchange argument to show which rule is optimal and why the other two lose.
What Makes a Greedy Choice Safe
A greedy algorithm makes one choice per step and never takes it back. That is only correct when the choice can never cost you the best answer. Two properties make it safe.
The greedy choice property: among all the optimal answers, at least one starts with the choice greedy makes. You do not need greedy's answer to be the only optimum, just one of them.
Optimal substructure: once that first choice is made, what is left is a smaller copy of the same problem, and an optimal answer to it plus the first choice is optimal for the whole. Put the two together and induction finishes the job: the first choice is safe, the rest is the same problem again.
- Greedy choice property: the first greedy move appears in some optimal answer
- Optimal substructure: the leftover problem has the same shape
- Both hold: greedy is optimal. Either fails: look for a counterexample
The Problem: Ordering Jobs on One Machine
Four jobs share one machine, which runs one job at a time without breaks. Job A takes 4 hours, B takes 1, C takes 3 and D takes 2. Each job finishes at some time, and we want the sum of finish times to be as small as possible. That is the same as keeping the average wait short.
In the order A, B, C, D the finish times are 4, 5, 8 and 10, a sum of 27. Running the longest job first (A, C, D, B) gives 30. Running the shortest first (B, D, C, A) gives 1, 3, 6 and 10, a sum of 20. Twenty is the best of the three, but three tries prove nothing. There are 24 orders here and n! in general, so we need an argument, not a search.
The Exchange Argument, Step by Step
- Take any order, for example an optimal one, and suppose it is not greedy's
- Find two neighbouring jobs that greedy would put the other way round
- Swap them and measure the change. Jobs before the pair finish at the same times; jobs after the pair also finish at the same times, because the pair takes the same total time
- Show the change is never positive
- Repeat. Each swap removes one out-of-order pair, so after a finite number of swaps you reach greedy's order, and the cost never went up on the way
The exchange argument compares any answer with greedy's and shows that you can turn it into greedy's, one small swap at a time, without ever making it worse. If that is true, greedy's answer is at least as good as every other answer, including the best one.
- Shortest first: if job i, taking t(i) hours, sits right before a shorter job j, swapping makes j finish t(i) earlier and i finish t(j) later
- Change = t(j) − t(i), which is negative because t(j) < t(i)
- From A, B, C, D the swaps go 27 → 24 → 23 → 21 → 20, ending at B, D, C, A
Terms, operations, and practical uses
Key terms
- Greedy choice propertySome optimal answer begins with the choice the greedy rule makes.
- Optimal substructureAfter the first choice, the rest is a smaller instance of the same problem.
- Exchange argumentSwap neighbours that break the greedy rule and show the cost never rises.
- InversionA pair of neighbouring items in the opposite order to the one greedy would use.
- Smith's ruleOrder jobs by weight divided by processing time, largest first, to minimise weighted finish time.
Related lessons and problems
- Greedy AlgorithmsThe overview: sort keys, classic problems, greedy vs dynamic programming.
- Activity Selection ProblemEarliest finish time, proved with an exchange.
- Interval AlgorithmsSorting ranges so that one pass is enough.
- Huffman CodingA greedy merge with an exchange proof on the code tree.
- Job Sequencing Problem (problem)Deadlines and profits, solved greedily.
Code in Python, C++ and Java
from functools import cmp_to_key
from itertools import permutations
JOBS = [("A", 4, 6), ("B", 1, 2), ("C", 3, 3), ("D", 2, 1)]
def total_cost(order, weighted=True):
clock = cost = 0
for name, t, w in order:
clock += t
cost += clock * (w if weighted else 1)
return cost
def by_ratio(a, b):
# a before b when w_a / t_a > w_b / t_b, compared without division
left, right = a[2] * b[1], b[2] * a[1]
return -1 if left > right else (1 if left < right else 0)
def names(order):
return " ".join(job[0] for job in order)
shortest = sorted(JOBS, key=lambda job: job[1])
heaviest = sorted(JOBS, key=lambda job: -job[2])
ratio = sorted(JOBS, key=cmp_to_key(by_ratio))
best = min(total_cost(p) for p in permutations(JOBS))
print("shortest first:", names(shortest), "| sum of finish times", total_cost(shortest, False))
print("shortest first, weighted:", total_cost(shortest))
print("heaviest first, weighted:", names(heaviest), total_cost(heaviest))
print("ratio w/t first, weighted:", names(ratio), total_cost(ratio))
print("best of all 24 orders:", best)#include <algorithm>
#include <iostream>
#include <string>
#include <vector>
using namespace std;
struct Job { char name; long long t, w; };
long long totalCost(const vector<Job>& order, bool weighted = true) {
long long clock = 0, cost = 0;
for (const Job& j : order) {
clock += j.t;
cost += clock * (weighted ? j.w : 1);
}
return cost;
}
string names(const vector<Job>& order) {
string s;
for (const Job& j : order) { if (!s.empty()) s += ' '; s += j.name; }
return s;
}
int main() {
const vector<Job> jobs = {{'A', 4, 6}, {'B', 1, 2}, {'C', 3, 3}, {'D', 2, 1}};
vector<Job> shortest = jobs, heaviest = jobs, ratio = jobs;
stable_sort(shortest.begin(), shortest.end(), [](const Job& a, const Job& b) { return a.t < b.t; });
stable_sort(heaviest.begin(), heaviest.end(), [](const Job& a, const Job& b) { return a.w > b.w; });
// a before b when w_a / t_a > w_b / t_b, compared without division
stable_sort(ratio.begin(), ratio.end(), [](const Job& a, const Job& b) { return a.w * b.t > b.w * a.t; });
vector<Job> p = jobs;
sort(p.begin(), p.end(), [](const Job& a, const Job& b) { return a.name < b.name; });
long long best = totalCost(p);
while (next_permutation(p.begin(), p.end(), [](const Job& a, const Job& b) { return a.name < b.name; }))
best = min(best, totalCost(p));
cout << "shortest first: " << names(shortest) << " | sum of finish times " << totalCost(shortest, false) << "\n";
cout << "shortest first, weighted: " << totalCost(shortest) << "\n";
cout << "heaviest first, weighted: " << names(heaviest) << " " << totalCost(heaviest) << "\n";
cout << "ratio w/t first, weighted: " << names(ratio) << " " << totalCost(ratio) << "\n";
cout << "best of all 24 orders: " << best << "\n";
}import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
public class Main {
record Job(String name, long t, long w) {}
static long totalCost(List<Job> order, boolean weighted) {
long clock = 0, cost = 0;
for (Job j : order) {
clock += j.t();
cost += clock * (weighted ? j.w() : 1);
}
return cost;
}
static String names(List<Job> order) {
StringBuilder sb = new StringBuilder();
for (Job j : order) sb.append(sb.length() > 0 ? " " : "").append(j.name());
return sb.toString();
}
static long best(List<Job> rest, List<Job> chosen) {
if (rest.isEmpty()) return totalCost(chosen, true);
long b = Long.MAX_VALUE;
for (int i = 0; i < rest.size(); i++) {
List<Job> r = new ArrayList<>(rest);
List<Job> c = new ArrayList<>(chosen);
c.add(r.remove(i));
b = Math.min(b, best(r, c));
}
return b;
}
public static void main(String[] args) {
List<Job> jobs = Arrays.asList(new Job("A", 4, 6), new Job("B", 1, 2), new Job("C", 3, 3), new Job("D", 2, 1));
List<Job> shortest = new ArrayList<>(jobs), heaviest = new ArrayList<>(jobs), ratio = new ArrayList<>(jobs);
shortest.sort(Comparator.comparingLong(Job::t));
heaviest.sort(Comparator.comparingLong((Job j) -> j.w()).reversed());
// a before b when w_a / t_a > w_b / t_b, compared without division
ratio.sort((a, b) -> Long.compare(b.w() * a.t(), a.w() * b.t()));
System.out.println("shortest first: " + names(shortest) + " | sum of finish times " + totalCost(shortest, false));
System.out.println("shortest first, weighted: " + totalCost(shortest, true));
System.out.println("heaviest first, weighted: " + names(heaviest) + " " + totalCost(heaviest, true));
System.out.println("ratio w/t first, weighted: " + names(ratio) + " " + totalCost(ratio, true));
System.out.println("best of all 24 orders: " + best(jobs, new ArrayList<>()));
}
}Step through it
Running on jobs A 4 h w6, B 1 h w2, C 3 h w3, D 2 h w1
When the Obvious Key Is Wrong
Now give each job a weight, how much each hour of waiting for it costs: A 6, B 2, C 3, D 1. The goal becomes the sum of weight × finish time. Shortest first still gives B, D, C, A, but its weighted cost is 83. Heaviest first (A, C, B, D) gives 71. Neither is the best.
Run the same swap. With job i right before job j, j finishes t(i) earlier and saves w(j)·t(i); i finishes t(j) later and costs w(i)·t(j). The swap helps exactly when w(j)·t(i) > w(i)·t(j), that is when w(j)/t(j) > w(i)/t(i). So the safe order sorts by weight divided by time, largest first. That is B (2), A (1.5), C (1), D (0.5), with a weighted cost of 66. Trying all 24 orders confirms that 66 is the minimum and that no other order reaches it.
This is the useful habit: do not guess the key and then try to prove it. Write down what one swap changes, and read the key off the inequality. The rule is known as Smith's rule, and the unweighted case is the same idea as shortest job first scheduling on a CPU.
| Rule | Order | Sum of finish times | Weighted cost |
|---|---|---|---|
| As given | A B C D | 27 | 68 |
| Shortest first | B D C A | 20 | 83 |
| Heaviest first | A C B D | 29 | 71 |
| Largest w/t first | B A C D | 24 | 66 |
Ties and Other Edge Cases
If two neighbouring jobs have the same w/t, the swap changes the cost by exactly 0, so either order is optimal. The proof still works: it only needs each swap not to make things worse.
Integer weights and times can be compared as w(j)·t(i) > w(i)·t(j) instead of dividing, which avoids floating-point error. A job with time 0 never delays anyone, so it can go first. With one job, or none, every order is the same.
Greedy Stays Ahead
The second standard proof style is greedy stays ahead. Instead of transforming another answer, you compare the two step by step and show that after every step greedy is at least as far along by some measure.
Activity selection is the usual example. After choosing k activities, greedy's k-th activity finishes no later than the k-th activity of any other valid schedule. If greedy always finishes earlier, it always has at least as much room left, so it can never end up with fewer activities. Exchange arguments suit ordering problems like the one above; stays-ahead suits problems where you pick items one at a time and count them.
- Exchange argument: turn any answer into greedy's without loss
- Greedy stays ahead: greedy leads on some measure after every step
- Both rest on the same two properties; pick whichever is easier to state
When Does Greedy Fail
The weighted example shows the most common failure: a rule that looks sensible, such as shortest first or heaviest first, but that breaks the swap inequality on some pair. A proof attempt usually tells you why. If you cannot show that the swap never hurts, try to build two jobs where it does, and you have a counterexample.
Greedy fails outright when no swap is local, that is when changing one choice changes which other choices are still allowed. Taking whole items into a fixed budget is the classic case; there, dynamic programming is the usual fix.
A cheap test catches most wrong rules before you spend time proving them: write a brute-force solver that tries every order on inputs of 5 to 8 items, generate random small cases, and compare it with the greedy answer. Any mismatch is a counterexample you can study.
- Write the cost change of one swap; the key falls out of it
- No safe swap? Build a two-item counterexample
- Brute force on small random inputs before you trust a rule
Related Problems
Each of these has a short greedy solution and a proof of exactly the kind above. Before coding, say which choice is safe and why.
- Assign Cookies: smallest cookie that satisfies the least greedy child
- Job Sequencing Problem: profit first, each job as late as its deadline allows
- Fractional Knapsack: value per weight, the same ratio idea as above
- Gas Station: a stays-ahead style argument about the running fuel total
- Partition Labels: close a part at the last position of every letter seen so far