The Greedy-Choice Property and Exchange Arguments
Activity selection went through three stages: a DP that tried every choice, a theorem saying one particular choice is always safe, and an algorithm that makes that choice and moves on. This lesson extracts the general recipe, names the two properties a greedy algorithm needs, and practises the main proof technique, the exchange argument, on two new problems. It also shows a greedy algorithm that looks right and is not, because recognising that is half of the skill.
Two properties
A greedy algorithm builds a solution by a sequence of choices, each one made by a simple local rule and never undone. It is correct when the problem has:
- The greedy-choice property. There is an optimal solution that contains the greedy choice. So committing to it loses nothing.
- Optimal substructure. After the greedy choice, what remains is a smaller instance of the same problem, and an optimal solution of the remainder combined with the greedy choice is optimal for the whole.
Together they give correctness by induction on the size of the instance: the first choice is safe by (1), and the rest is solved optimally by induction and (2).
The difference from dynamic programming is when the choice is made. A DP makes its choice after solving the subproblems for every option, because it cannot know in advance which option wins. A greedy algorithm makes the choice first, using only local information, and then solves the single subproblem that remains. That is why greedy algorithms are usually much faster, and why they need the extra property (1).
The general recipe:
- Cast the problem as "make one choice, leaving one subproblem".
- Prove that some optimal solution makes the greedy choice, usually by an exchange argument: take any optimal solution, and show it can be modified into one that makes the greedy choice without getting worse.
- Prove optimal substructure: the greedy choice plus an optimal solution of the remainder is optimal.
When greedy fails: making change
Pay an amount with as few coins as possible, from denominations , unlimited supply. The greedy rule takes the largest coin that fits, repeatedly. For euro or US coins this is optimal, but that is a property of those coin systems, not of the rule. The program compares greedy with an exact DP (the unbounded-knapsack recurrence ) and reports the smallest amount where greedy loses.
def greedy_coins(n, coins):
count = 0
for d in sorted(coins, reverse=True):
count += n // d
n %= d
return count
def optimal_coins(limit, coins):
C = [0] + [None] * limit
for n in range(1, limit + 1):
C[n] = 1 + min(C[n - d] for d in coins if d <= n)
return C
for coins in [(1, 2, 5, 10, 20, 50), (1, 5, 10, 25), (1, 4, 6), (1, 3, 4), (1, 7, 10), (1, 2, 4, 8)]:
C = optimal_coins(200, coins)
bad = next((n for n in range(1, 201) if greedy_coins(n, coins) > C[n]), None)
if bad is None:
print(f"coins {coins}: greedy optimal for every amount up to 200")
else:
print(f"coins {coins}: greedy fails first at {bad}: greedy {greedy_coins(bad, coins)} coins, optimum {C[bad]}")coins (1, 2, 5, 10, 20, 50): greedy optimal for every amount up to 200
coins (1, 5, 10, 25): greedy optimal for every amount up to 200
coins (1, 4, 6): greedy fails first at 8: greedy 3 coins, optimum 2
coins (1, 3, 4): greedy fails first at 6: greedy 3 coins, optimum 2
coins (1, 7, 10): greedy fails first at 14: greedy 5 coins, optimum 2
coins (1, 2, 4, 8): greedy optimal for every amount up to 200
With coins , the amount 8 is paid greedily as , three coins, but needs two. The greedy-choice property fails: no optimal solution for 8 contains a 6. Coin systems for which greedy is always optimal are called canonical, and there is an test for it (Pearson, 2005), but the safe general method is the DP.
An exchange argument: shortest job first
One machine must run jobs with processing times , one after another, starting at time 0. Job completes at time , the sum of the processing times of the jobs up to and including it. Minimise the total (equivalently the average) completion time , for example to minimise the average waiting time of customers at a counter.
Greedy rule: run the jobs in order of increasing processing time (shortest processing time first, SPT).
Exchange argument. Take any order that is not SPT. Then somewhere a job runs immediately before a job with . Swap the two. Jobs before them are unaffected, and so are jobs after them (the pair still occupies the same total time ). Before the swap the two completion times were and , where is the start of the pair; after the swap they are and . The total changes by : it strictly decreases. So a non-SPT order is never optimal, and since some order is optimal, it must be an SPT order (all SPT orders have the same total, as they differ only by swapping equal times).
Each such swap removes one inversion (a pair out of SPT order), which is the same bubble-sort reasoning used for inversions in Sorting & Order Statistics.
from itertools import permutations
def total_completion(times):
clock = total = 0
for t in times:
clock += t
total += clock
return total
jobs = [7, 2, 9, 4, 4, 1, 6]
spt = sorted(jobs)
best = min(total_completion(p) for p in permutations(jobs))
print("SPT order", spt, "total completion", total_completion(spt))
print("brute force over all", len(list(permutations(jobs))), "orders: best total", best)
print("longest first", sorted(jobs, reverse=True), "total", total_completion(sorted(jobs, reverse=True)))
# one exchange step, shown explicitly
order = [2, 9, 4]
print(f"{order} -> total {total_completion(order)}; swap 9 and 4 -> {[2, 4, 9]} total {total_completion([2, 4, 9])}"
f" (difference {total_completion([2, 4, 9]) - total_completion(order)} = 4 - 9)")SPT order [1, 2, 4, 4, 6, 7, 9] total completion 96
brute force over all 5040 orders: best total 96
longest first [9, 7, 6, 4, 4, 2, 1] total 168
[2, 9, 4] -> total 28; swap 9 and 4 -> [2, 4, 9] total 23 (difference -5 = 4 - 9)
Brute force over all 5040 orders confirms the SPT total, and the explicit swap of an adjacent inverted pair lowers the total by exactly , as the argument predicts. The running time is that of sorting, .
In C++
SPT is a sort plus a prefix sum. With weights (job matters times as much), the same exchange argument gives Smith's rule: order by increasing. The program checks Smith's rule against brute force with std::next_permutation.
#include <algorithm>
#include <climits>
#include <cstdio>
#include <vector>
struct Job { int t, w; };
long long weighted_total(const std::vector<Job>& jobs) {
long long clock = 0, total = 0;
for (const auto& j : jobs) { clock += j.t; total += j.w * clock; }
return total;
}
int main() {
std::vector<Job> jobs = {{7, 3}, {2, 1}, {9, 4}, {4, 4}, {1, 1}, {6, 2}};
auto smith = jobs;
std::stable_sort(smith.begin(), smith.end(),
[](const Job& a, const Job& b) { return a.t * b.w < b.t * a.w; }); // t/w increasing, no division
std::printf("Smith's rule:");
for (const auto& j : smith) std::printf(" (t=%d,w=%d)", j.t, j.w);
std::printf("\nweighted total %lld\n", weighted_total(smith));
auto perm = jobs;
std::sort(perm.begin(), perm.end(), [](const Job& a, const Job& b) { return a.t < b.t || (a.t == b.t && a.w < b.w); });
long long best = LLONG_MAX;
do best = std::min(best, weighted_total(perm));
while (std::next_permutation(perm.begin(), perm.end(),
[](const Job& a, const Job& b) { return a.t < b.t || (a.t == b.t && a.w < b.w); }));
std::printf("brute force best %lld\n", best);
}Smith's rule: (t=4,w=4) (t=1,w=1) (t=2,w=1) (t=9,w=4) (t=7,w=3) (t=6,w=2)
weighted total 219
brute force best 219
Exchange arguments in general
The three proofs so far share a shape. Fix an optimal solution and the greedy solution . Find the first place where they differ. Show that can be changed at that place to agree with (a swap, a replacement, a reordering) without making it worse and without breaking feasibility. Repeat, or argue by contradiction with a "closest to greedy" optimal solution. The details differ, but the questions to ask are always the same:
- What exactly is exchanged, and why is the result still a valid solution?
- Why is the result no worse, using only the rule greedy follows?
- Why does the process terminate, or why does "closest" exist?
The upcoming lessons use exactly this template for the fractional knapsack, Huffman codes and matroids. The DSA course's Greedy Algorithms lesson collects further everyday examples.
Test yourself
What distinguishes a greedy algorithm from dynamic programming?
- Greedy algorithms have no optimal substructure
- Greedy makes its choice before solving the remaining subproblem, using local information; DP compares all choices using solved subproblems
- Greedy algorithms use memoization
- DP algorithms never use sorting
With coins , how does greedy pay 6, and what is optimal?
- (3 coins); optimal (2 coins)
- (2 coins), optimal
- , optimal
- (6 coins); optimal 2
Jobs with times 5 and 2 run in the order 5, 2. How does swapping them change the total completion time?
- It increases by 3
- It decreases by 3
- It does not change
- It decreases by 7