Module contents
Lesson 14 of 33Core 100 min

Greedy algorithms, exchange arguments and matroids

Prove and refute greedy algorithms using stays-ahead and exchange arguments, then characterize optimal greedy selection with matroids.

After this lesson you can

  • Design greedy algorithms and find counterexamples when they are not optimal.
  • Prove optimality with stays-ahead and exchange arguments.
  • Verify matroid axioms in graphic, linear, uniform and partition examples.
  • Prove the Rado-Edmonds theorem and apply it to deadline scheduling.
  • Recognize when a greedy algorithm provides only an approximation, not an optimum.

Before you start

Motivation: the decision never revisited

A greedy algorithm builds a solution piece by piece, at each step choosing what seems best now without looking ahead or undoing anything. It is an especially tempting design idea, so it appears everywhere:

  • Codes and trees. Huffman repeatedly merges the two least frequent symbols, while Kruskal and Prim build minimum spanning trees by adding the cheapest edge that breaks nothing. All three are optimal, and the ideas for proving it (exchange and, for Kruskal, matroids) are this lesson’s subject.
  • Machine learning. A decision tree grows by selecting the highest-gain split at each node without considering later possibilities, so the resulting tree is not globally optimal. k-means++ initialization chooses centers greedily (randomized), and data or sensor selection with submodular functions is greedy by construction.
  • Text generation. A language model’s greedy decoding chooses the most likely token at each step. Imagine a two-step model. At the first, p(A)=0.5p(A) = 0.5, p(B)=0.4p(B) = 0.4 and p(C)=0.1p(C) = 0.1. If the first was AA, the most likely second token is xx with p(x∣A)=0.4p(x \mid A) = 0.4 (remaining mass is distributed); if it was BB, the second is zz with p(z∣B)=1p(z \mid B) = 1. Greedy chooses AA then xx, a sequence of probability 0.5×0.4=0.200.5 \times 0.4 = 0.20, whereas BzBz has probability 0.40.4. Greedy maximizes each factor separately, not the product.
  • Scheduling. Which task to run next in a job queue or how many rooms a set of meetings needs are problems with simple greedy rules.

Greedy algorithms have a bad reputation among those who have seen them fail and too good a reputation among those who have only seen them work. Both are justified: some greedy algorithms are optimal with a clean proof, others arbitrarily bad. Coin change is the simplest starting case. Paying an amount with the fewest coins seems to call for repeatedly choosing “the largest that fits”, and this works for euros or dollars. With another system it does not:

InteractiveCoin change: when greedy fails
Greedy for 6: 3 coins
41×2
Optimal for 6: 2 coins
3×2
Amounts 1 to 60: is greedy optimal?
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  • greedy is optimal
  • greedy uses extra coins (darker: 2 or more)
  • thick border: smallest counterexample
Amount 6 is the smallest where greedy fails: it pays 3 coins (4 + 1 + 1) where 2 suffice (3 + 3). One bad amount is enough to disprove greedy optimality.
6
Greedy coins3
Optimal coins2
Smallest counterexample6
Kozen–Zaks bound5 < x < 7
With coins {1,3,4}\{1, 3, 4\} and amount 66, greedy pays 4+1+14 + 1 + 1 (three coins) when 3+33 + 3 (two) suffices. The bottom strip marks in red, for each amount from 1 to 60, those where greedy uses extra coins. Try euro and dollar systems (all green), and build your own: remove coins or add one (1 is always present). Notice one bad amount suffices, and the first always lies within the interval indicated by ‘Kozen and Zaks bound’ (covered in the lab).

The lesson has three ideas. First, how to prove a greedy algorithm optimal: no mechanical recipe exists, but two arguments work in most cases and are learned through three scheduling problems. Second, how to disprove a false one: systematically search for counterexamples. Third, an exact characterization of when greedy works for every weight function: matroid structure and the Rado–Edmonds theorem.

The greedy paradigm and how to prove it

A greedy algorithm always has two ingredients: a notion of feasibility (which partial sets can be extended) and a selection rule (which candidate is preferred). Most design work is choosing the rule; proof work is checking that despite never looking back, the result cannot be improved. Two arguments are most useful.

Greedy stays ahead. Compare greedy step by step with any optimal solution and prove by induction that after each step greedy is at least as good according to a progress measure. At the end, “at least as good at every step” implies “at least as good overall.”

Exchange argument. Start from any optimal solution and transform it by local changes that never worsen value until it becomes the greedy solution. An exchange argument does not need the optimum to resemble greedy: it forces that resemblance without losing quality. It is the most versatile argument: use it for deadline queues, fractional knapsack, Huffman and finally matroids.

Notice an important asymmetry. One counterexample refutes a greedy algorithm; proving it needs a general argument. Counterexamples are searched for: a small instance with adversarial intent almost always reveals them, so distrust a greedy rule tested only on successful examples.

Interval scheduling

This models “one resource, many reservations”: a room, GPU or antenna. Many plausible greedy rules sort requests by a criterion and accept each if compatible with those accepted. Four candidates:

  1. Earliest start: smallest sis_i.
  2. Shortest: smallest fi−sif_i - s_i.
  3. Fewest conflicts: collides with the fewest remaining requests.
  4. Earliest finish: smallest fif_i.

All four sound reasonable and intuition cannot distinguish them. An adversary can. In the next interactive you draw instances and the computer compares each rule with the brute-force optimum:

InteractiveGreedy rule tournament
02468101214161820a1bcdRule: 1aOptimum: 3bcd
1 selected
  • chosen by rule (number = order)
  • discarded due to conflict
  • belongs to an optimum
«Earliest start» selects 1 interval but a schedule exists with 3: the rule is not correct.
Problem
Intervals nn4
Rule “Earliest start”1
Optimum (brute force)3
Verdictloses 2
Drag an interval to move it or its ends to stretch it; click a rule below to see its decisions (step by step with the player: each choice discards intervals that conflict). The final two strips compare the rule's choices with an optimum. Load each counterexample instance and click ‘Find counterexample’ for each rule: it finds one for the first three (‘fewest conflicts’ needs many more attempts) and none for ‘earliest finish’. In ‘Assign rooms’, the same interval set is assigned to rooms and the lower chart counts open intervals at each instant.

What you should have seen:

  • Earliest start loses with a very long interval starting first and blocking all others.
  • Shortest loses with a short interval straddling two long ones that fit together.
  • Fewest conflicts loses, but its counterexample must be constructed carefully: the figure’s instance, which fails under any tie breaking, has 11 intervals, and the button’s random search with 8 to 11 intervals usually needs thousands of instances (with smaller instances such as the lab’s, it may find none). A useful caution: a rarely failing rule looks correct.
  • Earliest finish never loses, in random search or your attempts. That proves nothing, but suggests a theorem. Here it is.
Proof

Let i1,…,iki_1, \dots, i_k be greedy’s chosen requests in selection order, and j1,…,jmj_1, \dots, j_m those of an optimal solution sorted by finish. Since compatible, they are also sorted by start and each starts no earlier than the preceding one ends. By optimality, k≤mk \le m.

Claim (greedy stays ahead): f(ir)≤f(jr)f(i_r) \le f(j_r) for every r≤kr \le k.

Base. i1i_1 is the request with earliest finish of all, so f(i1)≤f(j1)f(i_1) \le f(j_1).

Step. Suppose f(ir−1)≤f(jr−1)f(i_{r-1}) \le f(j_{r-1}). Request jrj_r starts no earlier than f(jr−1)f(j_{r-1}), hence no earlier than f(ir−1)f(i_{r-1}). All requests accepted so far end by f(ir−1)f(i_{r-1}), so jrj_r was compatible with them when greedy chose iri_r. Among candidates greedy takes the earliest finishing: f(ir)≤f(jr)f(i_r) \le f(j_r).

Cardinality. If k<mk < m, request jk+1j_{k+1} would exist and start no earlier than f(jk)≥f(ik)f(j_k) \ge f(i_k), by the claim. It would be compatible with everything greedy chose, so greedy could not have stopped after iki_k: contradiction (proof by contradiction). Thus k=mk = m.

∎

The proof shows why the rule is right: earliest finish leaves as much timeline free as possible for what follows, exactly the progress measure the argument needs. Each counterexample to the other rules is a failure of that measure: a long or straddling interval consumes time unnecessarily.

Sorting dominates implementation cost: O(nlog⁡n)\bigO(n \log n) with mergesort and O(n)\bigO(n) for the rest. By the comparison-sorting lower bound, an algorithm beginning with comparison sort cannot improve that.

Interval partitioning: a bound achieved by greedy

Now change the question: serve all requests using the fewest resources (rooms, processors). Interval partitioning distributes intervals into the smallest number of mutually compatible classes.

There is an obvious lower bound. The depth dd of an interval set is the largest number containing a single instant. Those dd intervals are pairwise incompatible, so any assignment needs at least dd rooms. Remarkably, that bound is always attained.

Proof

Let jj be the interval forcing room number k+1k + 1 to open. At that time the previous kk rooms are occupied: the last interval ii assigned to each satisfies fi>sjf_i > s_j, and since processed earlier, si≤sjs_i \le s_j. Those kk intervals and jj all contain instant sjs_j, so d≥k+1d \ge k + 1. Thus no room beyond the dd-th is ever opened.

∎

This is another greedy proof: compare not with an optimum but with a lower bound greedy attains. If no solution can go below a quantity and your algorithm matches it, you are done. To implement “first free room”, use a heap of (last interval finish, room) pairs: if the minimum has ended, reuse that room; otherwise open a new one. This gives O(nlog⁡n)\bigO(n \log n) total. The earlier interactive’s ‘Assign rooms’ mode shows it.

Minimize maximum lateness: exchange argument

Now each request is a task to complete in full without interruption on one machine. Task jj takes tjt_j and has deadline djd_j. Run in gapless order, task jj finishes at fjf_j and its lateness is ℓj=max⁡(0,fj−dj)\ell_j = \max(0, f_j - d_j).

Again reasonable rules exist: shortest first (clear the queue), least slack dj−tjd_j - t_j first (most urgent), earliest due date (EDD). The third looks most naive because it ignores durations, yet is correct. Why do the others fail?

  • Shortest first fails. With task (t,d)=(1,100)(t, d) = (1, 100) and another (10,10)(10, 10), running the short one first finishes the long one at 11, lateness 1. Running the long one first finishes it at 10 without lateness, and the short one at 11 with deadline 100: maximum lateness 0.
  • Least slack fails. With (1,2)(1, 2) and (10,10)(10, 10), slacks are 1 and 0. Doing the zero-slack task first finishes (10,10)(10, 10)‘s task at 10 and the other at 11, lateness 9. Deadline order does (1,2)(1, 2) first (finishes at 1) and the other finishes at 11, lateness 1.
  • Earliest due date is optimal, a result of Jackson (1955), whose proof is the canonical exchange argument.

First see the idea. The interactive takes any execution order (by default the worst, reverse deadline order) and repairs it through swaps of misordered adjacent pairs, showing lateness at every step:

InteractiveThe exchange that never worsens
Execution order0510155t = 2Job 5: duration 2, deadline 16, finishes at 2, lateness 04t = 4Job 4: duration 4, deadline 10, finishes at 6, lateness 03t = 1Job 3: duration 1, deadline 8, finishes at 7, lateness 06t = 1Job 6: duration 1, deadline 6, finishes at 8, lateness 21t = 3Job 1: duration 3, deadline 5, finishes at 11, lateness 62t = 3Job 2: duration 3, deadline 4, finishes at 14, lateness 10⇄⇄⇄⇄⇄Deadline (diamond), finish (circle) and lateness (red)1ℓ = 62ℓ = 10 (L)3456ℓ = 2Maximum lateness after each exchange (never increases)deadline order: 2100
  • duration tjt_j (block width)
  • deadline djd_j (flag and diamond)
  • lateness ℓj\ell_j
exchange 0 / 15
Initial state. Press play: each step swaps the first adjacent inversion (a job with a later deadline immediately before one with an earlier deadline).
Starting order
Current maximum lateness LL10
Initial LL10
LL in deadline order2
Inversions15
Exchange0 of 15
Each block is a task (width is duration); flags on the axis mark deadlines and each task has a row below with its deadline diamond, finish circle and lateness in red. Play: each step swaps an adjacent inversion (a later-deadline task immediately before an earlier-deadline one) and the lower graph records maximum lateness, which never rises. Change the starting order to ‘Shortest’ or ‘Slack’: these failing rules improve through exchanges until deadline order. Use the ⇄ buttons to manually swap a pair that is not an inversion and verify maximum lateness can then worsen.

The proof formalizes what you saw. Two preliminary observations simplify it. First, gaps are unhelpful: advancing a task after a gap worsens no finish time. Second, any order is a permutation σ\sigma of tasks, and an inversion is a task pair (i,j)(i, j) with ii executed before jj but di>djd_i > d_j. Deadline order is exactly the order without inversions. With equal deadlines, every inversion-free order has the same maximum lateness.

Proof

Step 1: all inversion-free orders have the same maximum lateness. Two inversion-free orders differ only in the order of equal-deadline tasks. Those tasks occupy a contiguous block ending at the same time in both orders, and the block’s maximum lateness is that of its last task, whose finish is always that time: it is the same for any internal order.

Step 2: if an order has an inversion, it has an adjacent inversion. If ii precedes jj with di>djd_i > d_j, inspect tasks between them: deadlines must decrease somewhere, and that decrease is an inverted adjacent pair.

Step 3: swapping an adjacent inversion does not increase maximum lateness. Let ii immediately precede jj with di>djd_i > d_j, and let ss be the starting time of ii. Other tasks’ finish times are unchanged. Before: fi=s+tif_i = s + t_i and fj=s+ti+tjf_j = s + t_i + t_j. After swapping: fj′=s+tj<fjf_j' = s + t_j < f_j and fi′=s+ti+tj=fjf_i' = s + t_i + t_j = f_j. Then

ℓj′=max⁡(0,fj′−dj)≤ℓj\ell_j' = \max(0, f_j' - d_j) \le \ell_j
Task jj now finishes earlier (fj′<fjf_j' < f_j) with the same deadline, so its lateness does not increase.
1/3

Step 4: conclusion. Each adjacent-inversion swap reduces inversion count by exactly one, a nonnegative integer at most (n2)\binom{n}{2}. Start from any optimal order and swap until no inversions remain in at most (n2)\binom{n}{2} steps; maximum lateness never rises. The result is inversion-free and by Step 1 has the same maximum lateness as deadline order. Since the optimum did not rise, deadline order is optimal.

∎

This exchange-argument pattern deserves a name: (1) fix an arbitrary optimum; (2) identify a disorder measure relative to greedy (here, inversions); (3) prove a local change reduces disorder without losing value; (4) conclude greedy is as good as optimum. Step 3 alone uses the particular greedy rule.

Fractional knapsack and Huffman

Two famous cases fit the same mold.

Fractional knapsack. There are nn items with value viv_i and weight wiw_i, and a knapsack of capacity WW; any fraction of each item may be taken. Greedy sorts by decreasing density vi/wiv_i / w_i and fills the knapsack until full. It is optimal by exchange: if an optimum takes weight δ>0\delta > 0 from item kk while leaving a denser item ii not fully taken (vi/wi≥vk/wkv_i/w_i \ge v_k/w_k), moving that weight δ\delta (or what remains of ii, if less) from kk to ii respects capacity and changes value by δ (vi/wi−vk/wk)≥0\delta\,(v_i/w_i - v_k/w_k) \ge 0. Repeating reaches greedy’s allocation.

But with indivisible items (0/1 knapsack), density-greedy fails. With values and weights (60,10)(60, 10), (100,20)(100, 20), (120,30)(120, 30) and capacity 50, greedy takes the first two for value 160160; the best is the last two, with 220220. The fraction available in the continuous case made exchange valid. 0/1 knapsack requires dynamic programming (pseudopolynomial).

Huffman. Given a frequency distribution, Huffman builds a minimum-average-length prefix code by repeatedly merging the two least frequent symbols. The key is an exchange lemma.

Proof

Let TT be an optimal tree and a,ba, b two sibling leaves of maximum depth (they exist: an optimal tree is full, meaning every internal node has two children, because a single-child node could be removed to shorten codes; hence a deepest leaf has a sibling, which is a leaf by maximum depth). Swap positions of xx and aa in TT. If da≥dxd_a \ge d_x are their depths and fa≥fxf_a \ge f_x frequencies, cost changes by −(fa−fx)(da−dx)≤0-(f_a - f_x)(d_a - d_x) \le 0: it does not rise. Do the same with yy and bb (if xx or yy already occupies one of those leaves, rename aa and bb so that leaf is its own and the swap unnecessary). The resulting tree is optimal and has xx and yy as deepest siblings.

∎

Merging xx and yy into a new symbol of frequency fx+fyf_x + f_y, the large tree’s cost is the reduced tree’s plus fx+fyf_x + f_y, so an optimum for the reduced problem gives one for the original, and induction on symbol count concludes (strong induction in practice). With frequencies 45,13,12,16,9,545, 13, 12, 16, 9, 5 (percent), the algorithm first merges 55 and 99, then 1212 and 1313, then 1414 and 1616, then 2525 and 3030 and finally 4545 and 5555: mean length 2.242.24 bits per symbol versus 33 for fixed length and entropy 2.222.22 bits.

Matroids

Several earlier problems have optimal greedy algorithms, but each proof was different. Is there a common structure explaining them all? For a huge family of problems there is: matroid theory, introduced by Whitney in 1935 to abstract linear independence.

(I1) and (I2) say I\mathcal{I} is a family of “feasible” sets closed under element removal. Everything special is in (I3): a smaller independent set can always grow with help from a larger one. See it in the main examples.

  • Uniform Uk,nU_{k,n}: EE has nn elements and independent sets have at most kk elements. (I3) is immediate: if ∣A∣<∣B∣≤k\abs{A} < \abs{B} \le k, any x∈B∖Ax \in B \setminus A works.
  • Partition: EE is divided into blocks E1,…,EmE_1, \dots, E_m with capacities c1,…,cmc_1, \dots, c_m, and an independent set has at most cic_i elements in each block EiE_i. If ∣A∣<∣B∣\abs{A} < \abs{B}, a block ii has ∣A∩Ei∣<∣B∩Ei∣≤ci\abs{A \cap E_i} < \abs{B \cap E_i} \le c_i (otherwise summing across blocks gives ∣B∣≤∣A∣\abs{B} \le \abs{A}), and any x∈(B∖A)∩Eix \in (B \setminus A) \cap E_i can be added.
  • Graphic: EE is a graph’s edge set and independent sets are forests (acyclic edge sets).
  • Linear: EE is a list of vectors and independent sets are linearly independent subsets.

The last two deserve proof.

Proof

Graphic. Let A,BA, B be forests with ∣A∣<∣B∣\abs{A} < \abs{B}. A forest with aa edges on NN vertices has N−aN - a connected components. If every edge of BB lay within components of AA, then BB would be a forest within those N−∣A∣N - \abs{A} components, and a forest on a component of cc vertices has at most c−1c - 1 edges; summing gives ∣B∣≤N−(N−∣A∣)=∣A∣\abs{B} \le N - (N - \abs{A}) = \abs{A}, absurd. Thus an edge of BB joins distinct components of AA: adding it closes no cycle.

Linear. Let A,BA, B be independent with ∣A∣<∣B∣\abs{A} < \abs{B}. Subspace span⁡A\spn A has dimension ∣A∣\abs{A}. If every vector of BB lay in span⁡A\spn A, the ∣B∣\abs{B} independent vectors of BB would inhabit a space of dimension ∣A∣<∣B∣\abs{A} < \abs{B}, impossible because more vectors than the dimension are dependent (Steinitz’s exchange lemma, and basis dimension is unique). Thus some x∈Bx \in B is outside span⁡A\spn A, and A∪{x}A \cup \{x\} is independent.

∎

And three natural systems that are not matroids:

  • Graph matchings. On path a−b−c−da - b - c - d with edges e1=abe_1 = ab, e2=bce_2 = bc, e3=cde_3 = cd, sets A={e2}A = \{e_2\} and B={e1,e3}B = \{e_1, e_3\} are matchings with ∣A∣<∣B∣\abs{A} < \abs{B}, and neither e1e_1 nor e3e_3 can be added to AA.
  • Independent vertex sets (no adjacent pair). On path a−b−ca - b - c, A={b}A = \{b\} and B={a,c}B = \{a, c\} violate (I3).
  • Knapsack: item sets of total weight ≤W\le W. With weights 5,3,35, 3, 3 and W=6W = 6, A={5}A = \{5\} and B={3,3}B = \{3, 3\} violate (I3).

All three satisfy (I1) and (I2), and such a system is called an independence system. What distinguishes a matroid is exactly (I3), and the next result shows why that axiom matters.

Proof

If B1,B2B_1, B_2 are bases with ∣B1∣<∣B2∣\abs{B_1} < \abs{B_2}, (I3) gives x∈B2∖B1x \in B_2 \setminus B_1 with B1∪{x}B_1 \cup \{x\} independent, so B1B_1 would not be maximal. Contradiction.

∎

The three negative examples visibly violate this: the three-edge path has a maximal one-edge matching ({e2}\{e_2\}) and another with two ({e1,e3}\{e_1, e_3\}). A greedy algorithm stuck in the first cannot be optimal with suitable weights. Beware the false converse: equal sizes for all bases of EE do not suffice. In a four-vertex cycle a−b−c−d−aa - b - c - d - a all maximal matchings have two edges and yet A={ab}A = \{ab\} and B={bc,da}B = \{bc, da\} violate (I3). What is equivalent to (I3) is the local version: for every X⊆EX \subseteq E, all maximal independent sets contained in XX have equal size (an augmentation-violating pair gives two of different sizes within X=A∪BX = A \cup B). Circuits are minimal dependent sets: cycles in the graphic matroid, minimal linearly dependent sets in the linear matroid, and in uniform Uk,nU_{k,n} (with k<nk < n) sets of k+1k + 1 elements. A set is independent if and only if it contains no circuit, so circuits describe the matroid as well as independent sets.

Now experiment. The next interactive checks (I1), (I2) and (I3) by enumerating all subsets and, when (I3) fails, shows a violating pair (A,B)(A, B). Change the system, edit the graph or drag vectors:

InteractiveIs it a matroid?
a6b3c7d4e8f2g5h9
  • no augmentation violation: no pair (A,B)(A, B) to color
Weights
✓ the empty set is independent  ✓ every subset of an independent set is independent  ✓ augmentation property
This is a matroid: for every pair of independent sets with ∣A∣<∣B∣|A| < |B| there is an element of B∖AB \setminus A that can be added to AA (checked against all 238 independent sets). All bases have 6 elements. Circuits (minimal dependent sets): {a, b, c, d, e, f}, {b, c, d, g, h}, {a, e, f, g, h}.
Set system
View
Elements8
Independent sets238
Rank (maximum size)6
Base sizes6
With ‘Augmentation axiom’, the interactive enumerates all independent sets and searches for a pair A,BA, B with ∣A∣<∣B∣\abs{A} < \abs{B} and no element of B∖AB \setminus A addable to AA; the pair is colored in the figure (blue AA, orange BB). Graph forests form a matroid; matchings of the same graph do not (also notice base sizes). In ‘Vectors’, drag tips to align two vectors and create a size-2 circuit. In ‘Deadlines’, each task takes one unit and a set is valid if for every tt it has at most tt tasks with deadline ≤t\le t. With ‘Greedy algorithm’, run greedy with editable weights against the optimum. The ‘Rado-Edmonds weights’ button constructs weights from a failing pair that fool greedy. It does this systematically, and you will prove it.

The Rado–Edmonds theorem

On matroid (E,I)(E, \mathcal{I}) with weights w:E→R≥0w : E \to \R_{\ge 0}, the problem is to find an independent set S∈IS \in \mathcal{I} of maximum weight w(S)=∑e∈Sw(e)w(S) = \sum_{e \in S} w(e). Matroid greedy is as simple as:

  1. Sort EE by decreasing weight: w(e1)≥w(e2)≥⋯≥w(en)w(e_1) \ge w(e_2) \ge \dots \ge w(e_n).
  2. Start with S=∅S = \varnothing. For i=1,…,ni = 1, \dots, n: if S∪{ei}∈IS \cup \{e_i\} \in \mathcal{I}, set S←S∪{ei}S \leftarrow S \cup \{e_i\}.

It uses the matroid only through an independence oracle (“is this set independent?”). And it works exactly when it should:

The theorem has two names: Rado published it in 1957 in independence-function language, and Edmonds rediscovered it in 1971 and placed it in the modern algorithmic framework (Gale also gave a version in 1968). The forward direction exemplifies “greedy stays ahead”; the converse constructs adversarial weights, which you will do below.

Proof

(Matroid implies optimal greedy.) Let G={g1,…,gk}G = \{g_1, \dots, g_k\} be greedy’s result in acceptance order, so w(g1)≥⋯≥w(gk)w(g_1) \ge \dots \ge w(g_k). GG is maximal: an element was rejected because it broke independence with a subset of GG, and heredity (I2) keeps that true later. By the bases proposition GG is a base and k=r(M)k = r(M). Let OO be a maximum-weight independent set. Since weights are nonnegative, OO can be extended to a base without lowering its weight, so assume O={o1,…,ok}O = \{o_1, \dots, o_k\} is a base ordered with w(o1)≥⋯≥w(ok)w(o_1) \ge \dots \ge w(o_k).

Claim (greedy stays ahead): w(gi)≥w(oi)w(g_i) \ge w(o_i) for every ii.

Otherwise let ii be the smallest index with w(gi)<w(oi)w(g_i) < w(o_i). Apply (I3) to A={g1,…,gi−1}A = \{g_1, \dots, g_{i-1}\} and B={o1,…,oi}B = \{o_1, \dots, o_i\}: since ∣A∣=i−1<i=∣B∣\abs{A} = i - 1 < i = \abs{B}, there is oj∈B∖Ao_j \in B \setminus A with A∪{oj}∈IA \cup \{o_j\} \in \mathcal{I} and j≤ij \le i, so w(oj)≥w(oi)>w(gi)w(o_j) \ge w(o_i) > w(g_i). Greedy examined ojo_j before gig_i (it has strictly greater weight). At that moment its set SS satisfied S⊆AS \subseteq A, so S∪{oj}⊆A∪{oj}∈IS \cup \{o_j\} \subseteq A \cup \{o_j\} \in \mathcal{I}, and (I2) forces S∪{oj}S \cup \{o_j\} to be independent: greedy would have accepted ojo_j. But then oj∈Ao_j \in A, contradicting oj∈B∖Ao_j \in B \setminus A.

Summing the claim, w(G)=∑iw(gi)≥∑iw(oi)=w(O)w(G) = \sum_i w(g_i) \ge \sum_i w(o_i) = w(O).

(Optimal greedy implies matroid.) This is the exercise “The converse of Rado–Edmonds” below.

∎

Three consequences justify the effort:

  • Kruskal is correct. The graphic matroid of a connected graph with NN vertices has spanning-tree bases, all with N−1N - 1 edges. With weights w′=M−ww' = M - w, where MM exceeds all weights, a maximum-w′w' tree is a minimum-ww tree (all have the same edge count), and greedy sorting by decreasing w′w' is Kruskal sorting by increasing ww. Checking “does it close a cycle?” checks graphic-matroid independence (in practice, with union-find).
  • Negative weights and bases. With negative weights, stop greedy on reaching the first nonpositive weight: negative-weight elements never help. For the maximum- or minimum-weight base, add a constant to all weights as just done: all bases have r(M)r(M) elements, so each weight changes by the same amount and the best stays best.
  • The theorem characterizes. Any problem whose greedy algorithm is optimal for all weights has matroid structure. Given a set system and asking whether weight-greedy works, (I3) decides.

The last sentence has fine print: not every optimal greedy algorithm is matroid greedy. Earliest finish is optimal for interval scheduling, but sets of compatible intervals do not form a matroid: with [0,10)[0, 10), [0,4)[0, 4) and [5,10)[5, 10), independent set {[0,10)}\{[0, 10)\} cannot be augmented by any element of {[0,4),[5,10)}\{[0, 4), [5, 10)\}. No contradiction: Rado and Edmonds concern greedy sorting by weight (and a weight function fools it), whereas earliest finish sorts by a different criterion, finish time, which is not a weight. The same holds for Huffman.

Unit-task scheduling with deadlines

One last example has no obvious greedy algorithm until the matroid is seen. There are nn unit-duration tasks; task ii has integer deadline did_i and profit pip_i received only if completed on time. Choose which tasks to perform and in what order to maximize profit.

A task set is schedulable if an order exists in which all finish on time. Deciding schedulability is easy:

Proof

(⇒\Rightarrow) Tasks with deadline ≤t\le t must occupy distinct slots within {1,…,t}\{1, \dots, t\}, so there can be at most tt. (⇐\Leftarrow) Run tasks by increasing deadline: the kk-th occupies slot kk. Its deadline dd satisfies Nd(S)≥kN_d(S) \ge k (that task and the preceding k−1k - 1 have deadline ≤d\le d), and Nd(S)≤dN_d(S) \le d by assumption, so k≤dk \le d.

∎
Proof

(I1) and (I2) are immediate. For (I3), let A,BA, B be schedulable with ∣A∣<∣B∣\abs{A} < \abs{B}, and let DD be the largest deadline. Since ND(B)=∣B∣>∣A∣=ND(A)N_D(B) = \abs{B} > \abs{A} = N_D(A), there is a largest k<Dk < D with Nk(B)≤Nk(A)N_k(B) \le N_k(A) (always true for k=0k = 0), and for every t>kt > k we have Nt(B)>Nt(A)N_t(B) > N_t(A). In particular Nk+1(B)−Nk(B)>Nk+1(A)−Nk(A),N_{k+1}(B) - N_k(B) > N_{k+1}(A) - N_k(A), because the left side minus the right is (Nk+1(B)−Nk+1(A))+(Nk(A)−Nk(B))>0\big(N_{k+1}(B) - N_{k+1}(A)\big) + \big(N_k(A) - N_k(B)\big) > 0. Thus BB has more tasks with deadline exactly k+1k + 1 than AA, and a task x∈B∖Ax \in B \setminus A exists with deadline k+1k + 1. Show A∪{x}A \cup \{x\} is schedulable. For t≤kt \le k nothing changes. For t≥k+1t \ge k + 1, Nt(A∪{x})=Nt(A)+1≤Nt(B)≤tN_t(A \cup \{x\}) = N_t(A) + 1 \le N_t(B) \le t (the first inequality because Nt(A)<Nt(B)N_t(A) < N_t(B) and they are integers). By the lemma it is schedulable.

∎

By Rado–Edmonds greedy is optimal: sort tasks by decreasing profit and accept each if the set remains schedulable. With tasks (d,p)(d, p) equal to (2,100)(2, 100), (1,19)(1, 19), (2,27)(2, 27), (1,25)(1, 25) and (3,15)(3, 15): accept 100100; accept 2727 (two have deadline ≤2\le 2, which fits); reject 2525 (three have deadline ≤2\le 2); reject 1919 too; accept 1515. Total profit 142142. An “earliest deadline first” or “highest profit among urgent tasks” algorithm would need its own proof: the matroid framework supplies one at once.

Beyond matroids

What if the system is not a matroid? Two useful situations retain greedy as a good tool, but no longer exact.

Matroid intersection. Many problems are intersections of two matroids: a bipartite graph matching is an edge set independent in two partition matroids simultaneously (at most one edge per left vertex, at most one per right vertex). For two matroids an exact polynomial-time algorithm exists (Edmonds), but is not greedy; for three the problem is NP-hard (it contains three-dimensional matching). Greedy on the intersection of pp matroids guarantees fraction 1/p1/p of optimum (Jenkyns 1976; Korte and Hausmann 1978), fraction 1/21/2 with two matroids.

Submodular functions. A set function ff is submodular if it has diminishing returns: adding an element to a large set contributes no more than adding it to a small one, namely f(A∪{x})−f(A)≥f(B∪{x})−f(B)f(A \cup \{x\}) - f(A) \ge f(B \cup \{x\}) - f(B) whenever A⊆BA \subseteq B and x∉Bx \notin B. The basic example is coverage: given subsets S1,…,SmS_1, \dots, S_m of a universe, f(T)=∣⋃i∈TSi∣f(T) = \abs{\bigcup_{i \in T} S_i}. Maximizing a monotone submodular function subject to ∣T∣≤k\abs{T} \le k is NP-hard, but greedy adding the largest marginal-gain element each step guarantees at least fraction 1−1/e≈0.6321 - 1/e \approx 0.632 of optimum (Nemhauser, Wolsey and Fisher, 1978), and that is the best possible maximum-coverage bound unless P = NP (Feige, 1998). With a matroid rather than cardinality constraint, greedy guarantees 1/21/2. This is the same lesson’s greedy algorithm with an approximation rather than optimality guarantee, explaining its use in sensor, training-data and feature selection. Minimum-cost greedy set cover has a logarithmic guarantee and appears with approximation ratios.

Lab 1: greedy algorithms with an optimality verifier

The first lab implements the three scheduling algorithms and subjects them to a verifier: brute force on small instances. A proof says greedy is correct, but a verifier protects against implementation mistakes (< where <= belonged breaks everything on ties) and helps find counterexamples to a greedy algorithm of unknown correctness.

[ ]Interval scheduling and partitioning, verifiedBrowser
import heapq, itertools, random

def compatibles(a, b):
    """Intervalos semiabiertos [s, f): si uno acaba donde empieza el otro, no chocan."""
    return a[1] <= b[0] or b[1] <= a[0]

def planificar(intervalos):
    """Voraz de «termina antes». Devuelve los índices elegidos. Coste: la ordenación, O(n log n)."""
    elegidos, ultimo_fin = [], float("-inf")
    for i in sorted(range(len(intervalos)), key=lambda i: intervalos[i][1]):
        s, f = intervalos[i]
        if s >= ultimo_fin:                 # compatible con todo lo elegido: basta mirar el último fin
            elegidos.append(i)
            ultimo_fin = f
    return elegidos

def optimo_bruto(intervalos):
    """Cardinalidad máxima de un conjunto compatible, probando todos los subconjuntos (n pequeño)."""
    n, mejor = len(intervalos), 0
    for mask in range(1 << n):
        idx = [i for i in range(n) if mask >> i & 1]
        if len(idx) > mejor and all(compatibles(intervalos[a], intervalos[b]) for a, b in itertools.combinations(idx, 2)):
            mejor = len(idx)
    return mejor

def particionar(intervalos):
    """Partición voraz: por inicio creciente, al aula que antes se libera si ya está libre. Montículo de (fin, aula)."""
    libres, aulas, asign = [], 0, [None] * len(intervalos)
    for i in sorted(range(len(intervalos)), key=lambda i: intervalos[i][0]):
        s, f = intervalos[i]
        if libres and libres[0][0] <= s:
            _, a = heapq.heappop(libres)
        else:
            a, aulas = aulas, aulas + 1
        asign[i] = a
        heapq.heappush(libres, (f, a))
    return asign, aulas

def profundidad(intervalos):
    """Máximo número de intervalos abiertos a la vez (en empates, el fin se procesa antes que el inicio)."""
    eventos = sorted([(s, 1) for s, f in intervalos] + [(f, -1) for s, f in intervalos])
    abiertos = mejor = 0
    for _, d in eventos:
        abiertos += d
        mejor = max(mejor, abiertos)
    return mejor

rnd = random.Random(7)
def aleatorios(n, horizonte=20, largo=7):
    out = []
    for _ in range(n):
        s = rnd.randint(0, horizonte - 1)
        out.append((s, s + rnd.randint(1, largo)))
    return out

# 1. «Termina antes» frente a la fuerza bruta
fallos = 0
for _ in range(300):
    iv = aleatorios(rnd.randint(1, 9))
    fallos += len(planificar(iv)) != optimo_bruto(iv)
print("planificación: instancias donde el voraz no alcanza el óptimo:", fallos, "de 300")

# 2. Partición: aulas del voraz = profundidad, y la asignación es válida
malas = 0
for _ in range(2000):
    iv = aleatorios(rnd.randint(1, 14), 25, 8)
    asign, aulas = particionar(iv)
    valida = all(compatibles(iv[a], iv[b]) for a, b in itertools.combinations(range(len(iv)), 2) if asign[a] == asign[b])
    malas += not (valida and aulas == profundidad(iv))
print("partición: instancias donde falla algo:", malas, "de 2000")

ejemplo = [(0, 6), (1, 4), (2, 9), (5, 8), (7, 12), (8, 11), (10, 15), (12, 17), (13, 16), (14, 19)]
print("ejemplo: aulas =", particionar(ejemplo)[1], "profundidad =", profundidad(ejemplo), "| intervalos elegidos al máximo:", planificar(ejemplo))

Zero failures in both checks. Partition verification checks both parts of the proof: valid assignment and room count equal to depth. Notice the example (also in the interactive): 4 rooms are needed and maximum scheduling has 4 intervals.

For maximum lateness, besides brute-force verification, we check the exchange lemma for what it is, a claim about each step: start from random permutations and repair adjacent inversions, checking maximum lateness never rises.

[ ]Maximum lateness: deadline rule and exchange lemma checkedBrowser
import itertools, random

def retraso_max(orden, tareas):
    """Retraso máximo de ejecutar las tareas (t, d) en ese orden, sin huecos: max(0, f - d)."""
    t, L = 0, 0
    for j in orden:
        t += tareas[j][0]
        L = max(L, t - tareas[j][1])
    return max(L, 0)

def por_plazos(tareas):
    """Voraz de Jackson: primero el plazo más cercano (EDD)."""
    return sorted(range(len(tareas)), key=lambda j: tareas[j][1])

def mas_corto(tareas):
    return sorted(range(len(tareas)), key=lambda j: tareas[j][0])

def menor_holgura(tareas):
    return sorted(range(len(tareas)), key=lambda j: tareas[j][1] - tareas[j][0])

def optimo_bruto(tareas):
    return min(retraso_max(p, tareas) for p in itertools.permutations(range(len(tareas))))

rnd = random.Random(3)
def instancia(n=6):
    return [(rnd.randint(1, 5), rnd.randint(2, 18)) for _ in range(n)]

reglas = {"plazos (EDD)": por_plazos, "más corto": mas_corto, "menor holgura": menor_holgura}
pierde = {k: 0 for k in reglas}
for _ in range(400):
    tareas = instancia(rnd.randint(2, 6))
    opt = optimo_bruto(tareas)
    for nombre, regla in reglas.items():
        pierde[nombre] += retraso_max(regla(tareas), tareas) > opt
print("instancias (de 400) donde la regla no es óptima:", pierde)

# El lema de intercambio, comprobado: partir de un orden cualquiera y arreglar inversiones adyacentes.
# El retraso máximo nunca sube y se llega al orden por plazos.
viola = pasos = 0
for _ in range(500):
    tareas = instancia(rnd.randint(2, 7))
    orden = list(range(len(tareas)))
    rnd.shuffle(orden)
    L = retraso_max(orden, tareas)
    while True:
        i = next((i for i in range(len(orden) - 1) if tareas[orden[i]][1] > tareas[orden[i + 1]][1]), None)
        if i is None:
            break
        orden[i], orden[i + 1] = orden[i + 1], orden[i]
        L2 = retraso_max(orden, tareas)
        viola += L2 > L
        L, pasos = L2, pasos + 1
print("intercambios de inversiones realizados:", pasos, "| veces que el retraso máximo subió:", viola)

base = [(3, 5), (3, 4), (1, 8), (4, 10), (2, 16), (1, 6)]   # el ejemplo del interactivo
for nombre, regla in reglas.items():
    print(f"{nombre:14s} orden {[j + 1 for j in regla(base)]}  L = {retraso_max(regla(base), base)}")
print("óptimo por fuerza bruta:", optimo_bruto(base))

The deadline rule never loses; shortest loses on over half of random instances and least slack on about one in six. The second experiment’s 2190 exchanges never increased maximum lateness, showing proof step 3 at scale.

Now a counterexample finder, the general tool: it takes a greedy rule, instance generator and exact optimum, and returns the smallest instance where the rule loses. Apply it to four interval rules, coin change and knapsack.

[ ]A counterexample finder: intervals, coins and knapsackBrowser
import itertools, random

def compatibles(a, b):
    return a[1] <= b[0] or b[1] <= a[0]

def voraz_intervalos(iv, clave):
    """Voraz genérico de planificación: repite «elige el de menor clave y descarta los que chocan con él»."""
    resto, elegidos = list(range(len(iv))), []
    while resto:
        k = min(resto, key=lambda i: (clave(iv, resto, i), i))
        elegidos.append(k)
        resto = [j for j in resto if j != k and compatibles(iv[k], iv[j])]
    return elegidos

REGLAS = {
    "empieza antes": lambda iv, resto, i: iv[i][0],
    "más corto":     lambda iv, resto, i: iv[i][1] - iv[i][0],
    "menos choques": lambda iv, resto, i: sum(1 for j in resto if j != i and not compatibles(iv[i], iv[j])),
    "termina antes": lambda iv, resto, i: iv[i][1],
}

def optimo(iv):
    """Máximo conjunto compatible, por búsqueda con poda."""
    n, mejor = len(iv), 0
    def rec(i, elegidos):
        nonlocal mejor
        if len(elegidos) + n - i <= mejor:
            return
        if i == n:
            mejor = len(elegidos)
            return
        if all(compatibles(iv[i], iv[j]) for j in elegidos):
            rec(i + 1, elegidos + [i])
        rec(i + 1, elegidos)
    rec(0, [])
    return mejor

def buscar_contraejemplo(regla, generar, intentos, semilla=0):
    """Devuelve (instancia más pequeña donde la regla pierde, cuántas veces perdió) tras `intentos` instancias."""
    rnd = random.Random(semilla)
    mejor, fallos = None, 0
    for _ in range(intentos):
        iv = generar(rnd)
        if len(voraz_intervalos(iv, regla)) < optimo(iv):
            fallos += 1
            if mejor is None or len(iv) < len(mejor):
                mejor = iv
    return mejor, fallos

def generar(rnd):
    n = rnd.randint(3, 10)
    iv = []
    for _ in range(n):
        s = rnd.randint(0, 14)
        iv.append((s, s + rnd.randint(2, 5)))
    return iv

for nombre, regla in REGLAS.items():
    ce, fallos = buscar_contraejemplo(regla, generar, 1500)
    print(f"{nombre:14s} pierde en {fallos:4d} de 1500 instancias" + (f"; la más pequeña: {sorted(ce)}" if ce else ""))

# --- cambio de monedas ---
def voraz_monedas(monedas, x):
    n = 0
    for c in sorted(monedas, reverse=True):
        n, x = n + x // c, x % c
    return n

def optimo_monedas(monedas, tope):
    """Mínimo de monedas para cada importe 0..tope, por programación dinámica."""
    m = [0] + [10**9] * tope
    for x in range(1, tope + 1):
        m[x] = min(m[x - c] + 1 for c in monedas if c <= x)
    return m

def primer_fallo(monedas):
    tope = 3 * max(monedas)
    m = optimo_monedas(monedas, tope)
    return next((x for x in range(1, tope + 1) if voraz_monedas(monedas, x) > m[x]), None)

for sistema in ([1, 3, 4], [1, 2, 5, 10, 20, 50], [1, 5, 10, 25], [1, 5, 10, 12, 25], [1, 5, 10, 20, 25]):
    print(sistema, "-> menor importe donde el voraz falla:", primer_fallo(sistema))

# Cota de Kozen y Zaks: el menor contraejemplo x cumple c_3 + 1 < x < c_(n-1) + c_n
rnd = random.Random(0)
no_canonicos = fuera = 0
for _ in range(600):
    c = sorted([1] + rnd.sample(range(2, 40), rnd.randint(2, 5)))
    x = primer_fallo(c)
    if x is not None:
        no_canonicos += 1
        fuera += not (c[2] + 1 < x < c[-2] + c[-1])
print("sistemas no canónicos:", no_canonicos, "| fuera de la cota de Kozen-Zaks:", fuera)

# --- mochila: fraccionaria (voraz óptimo) frente a 0/1 (voraz falla) ---
objetos, capacidad = [(60, 10), (100, 20), (120, 30)], 50      # (valor, peso)
orden = sorted(objetos, key=lambda o: o[0] / o[1], reverse=True)
libre, fraccionaria, cero_uno = capacidad, 0.0, 0
for v, p in orden:
    tomar = min(1.0, libre / p)
    fraccionaria, libre = fraccionaria + tomar * v, libre - tomar * p
libre = capacidad
for v, p in orden:
    if p <= libre:
        cero_uno, libre = cero_uno + v, libre - p
mejor01 = max(sum(v for (v, p), t in zip(objetos, m) if t) for m in itertools.product([0, 1], repeat=3)
              if sum(p for (v, p), t in zip(objetos, m) if t) <= capacidad)
print(f"mochila: voraz fraccionario = {fraccionaria}, voraz 0/1 = {cero_uno}, óptimo 0/1 = {mejor01}")

Three observations. Earliest start and shortest fail on 12% and 6% of random instances respectively, with counterexamples of only three intervals, found quickly. Fewest conflicts fails not once in 1500 instances despite being wrong: random search is a weak test for rarely failing rules, so the interactive’s 11-interval counterexample required more time and intervals (and checking all tie breaks). The smallest amount where greedy fails in {1,5,10,12,25}\{1, 5, 10, 12, 25\} is 1515 (12+1+1+112 + 1 + 1 + 1 versus 10+510 + 5), in {1,5,10,20,25}\{1, 5, 10, 20, 25\} is 4040 (25+10+525 + 10 + 5 versus 20+2020 + 20), and euro and dollar systems are canonical. The Kozen–Zaks bound says the smallest counterexample xx of a system 1=c1<⋯<cn1 = c_1 < \dots < c_n with n≥3n \ge 3 satisfies c3+1<x<cn−1+cnc_3 + 1 < x < c_{n-1} + c_n; it holds for all noncanonical systems tested. This decides canonicity by checking only small amounts (the coding exercise uses it). A more refined polynomial algorithm also exists (Pearson, 2005).

Lab 2: matroid greedy in action

The second lab writes generic greedy, needing only an independence oracle, and runs it on four systems: graph forests, independent vector sets (using NumPy rank), deadline tasks and matchings. Brute force compares against optimum for random weights, and it implements the Rado–Edmonds converse: find pair (A,B)(A, B) violating augmentation and construct weights that fool greedy.

[ ]Generic oracle greedy and the Rado–Edmonds converseBrowser
import itertools, random
import numpy as np

# ---------- el voraz genérico: solo necesita un oráculo de independencia ----------
def voraz(elementos, peso, independiente):
    """Recorre los elementos por peso decreciente y conserva cada uno si el conjunto sigue siendo independiente."""
    S = []
    for e in sorted(elementos, key=lambda e: -peso[e]):
        if independiente(S + [e]):
            S.append(e)
    return S

def optimo_bruto(elementos, peso, independiente):
    """Peso máximo de un independiente, enumerando todos los subconjuntos."""
    mejor = 0
    for r in range(len(elementos) + 1):
        for S in itertools.combinations(elementos, r):
            if independiente(list(S)):
                mejor = max(mejor, sum(peso[e] for e in S))
    return mejor

# ---------- cuatro sistemas de conjuntos ----------
ARISTAS = [(0, 1), (1, 2), (2, 3), (3, 0), (0, 2), (3, 4), (4, 5), (5, 3)]   # índices de arista 0..7

def es_bosque(S):
    padre = list(range(6))
    def raiz(x):
        while padre[x] != x:
            padre[x] = padre[padre[x]]
            x = padre[x]
        return x
    for e in S:
        u, v = map(raiz, ARISTAS[e])
        if u == v:
            return False
        padre[u] = v
    return True

def es_emparejamiento(S):
    vertices = [x for e in S for x in ARISTAS[e]]
    return len(vertices) == len(set(vertices))

VECTORES = np.array([[1, 0, 0], [2, 0, 0], [0, 1, 0], [1, 1, 0], [0, 0, 1], [1, 1, 1], [0, 1, 1]], dtype=float)
def son_independientes(S):
    return len(S) == 0 or np.linalg.matrix_rank(VECTORES[list(S)]) == len(S)

PLAZOS = [2, 1, 2, 3, 1, 4, 4, 1]       # tarea i tiene plazo PLAZOS[i]; todas duran una unidad
def planificable(S):
    return all(sum(1 for i in S if PLAZOS[i] <= t) <= t for t in range(1, max(PLAZOS) + 1))

# ---------- el recíproco de Rado-Edmonds, hecho código ----------
def violacion_aumento(elementos, independiente):
    """Devuelve (A, B) independientes con |A| < |B| y sin ningún x de B∖A tal que A+x sea independiente, o None."""
    indep = [set(S) for r in range(len(elementos) + 1) for S in itertools.combinations(elementos, r) if independiente(list(S))]
    indep.sort(key=len)
    for B in indep:
        for A in indep:
            if len(A) < len(B) and not any(independiente(list(A | {x})) for x in B - A):
                return A, B
    return None

def pesos_adversos(elementos, A, B):
    q = len(A - B)
    return {e: (q + 2 if e in A else q + 1 if e in B else 0) for e in elementos}

sistemas = {
    "bosques (matroide gráfico)": (list(range(len(ARISTAS))), es_bosque),
    "vectores (matroide lineal)": (list(range(len(VECTORES))), son_independientes),
    "tareas con plazos":          (list(range(len(PLAZOS))), planificable),
    "emparejamientos":            (list(range(len(ARISTAS))), es_emparejamiento),
}

rnd = random.Random(1)
for nombre, (E, indep) in sistemas.items():
    fallos = 0
    for _ in range(60):
        w = {e: rnd.randint(0, 9) for e in E}
        fallos += sum(w[e] for e in voraz(E, w, indep)) < optimo_bruto(E, w, indep)
    v = violacion_aumento(E, indep)
    print(f"{nombre:27s} voraz subóptimo con pesos aleatorios: {fallos:3d} de 60 | ", "aumento se cumple" if v is None else f"viola el aumento: A={sorted(v[0])}, B={sorted(v[1])}")
    if v is not None:
        w = pesos_adversos(E, *v)
        S = voraz(E, w, indep)
        print(f"{'':27s} con los pesos de la demostración: voraz = {sum(w[e] for e in S)}, óptimo = {optimo_bruto(E, w, indep)}")

All three matroids pass all tests and matchings fail with random weights in a notable fraction of cases. Random weights need luck; weights built from the augmentation-violating pair make failure certain. The pair found, A={1}A = \{1\} and B={0,2}B = \{0, 2\}, is from path a−b−c−da - b - c - d in the matroid section (code edges 0, 1 and 2 form that path). With q=1q = 1, edge AA weighs 33 and edges B∖AB \setminus A weigh 22: greedy takes the 33-weight edge and ends with 33, whereas optimum is 44. This executes the argument in the exercise below.

With libraries: Kruskal is greedy on the graphic matroid and scipy.sparse.csgraph.minimum_spanning_tree must give the same weight. For the linear matroid, numpy.linalg.matrix_rank is the independence oracle. For maximum coverage, submodular greedy comfortably meets its guarantee on random instances, though it can lose on a constructed case.

[ ]Kruskal versus scipy, maximum-weight linear basis and submodular coverageBrowser
import itertools, random
import numpy as np
from scipy.sparse import coo_matrix
from scipy.sparse.csgraph import minimum_spanning_tree

# ---- Kruskal = voraz sobre el matroide gráfico (pesos crecientes: mínimo en lugar de máximo) ----
def kruskal(n, aristas):
    padre = list(range(n))
    def raiz(x):
        while padre[x] != x:
            padre[x] = padre[padre[x]]
            x = padre[x]
        return x
    total, arbol = 0.0, []
    for w, u, v in sorted(aristas):
        a, b = raiz(u), raiz(v)
        if a != b:                           # la arista no cierra ciclo: A + e sigue siendo un bosque
            padre[a] = b
            total += w
            arbol.append((u, v))
    return total, arbol

rnd = np.random.default_rng(0)
dif = 0.0
for _ in range(40):
    n = 12
    pesos = {(u, u + 1): 1000.0 + u for u in range(n - 1)}            # una cadena cara asegura que el grafo es conexo
    for u in range(n):
        for v in range(u + 1, n):
            if rnd.random() < 0.4:
                pesos[(u, v)] = float(rnd.integers(1, 100)) + rnd.random() * 1e-3
    aristas = [(w, u, v) for (u, v), w in pesos.items()]
    w, us, vs = zip(*aristas)
    M = coo_matrix((w, (us, vs)), shape=(n, n)).tocsr()
    dif = max(dif, abs(minimum_spanning_tree(M).sum() - kruskal(n, aristas)[0]))
print("Kruskal frente a scipy.sparse.csgraph.minimum_spanning_tree, diferencia máxima en 40 grafos:", round(dif, 9))

# ---- base de vectores de peso máximo: voraz con matrix_rank como oráculo ----
def base_voraz(X, peso):
    S = []
    for i in np.argsort(-peso, kind="stable"):
        if np.linalg.matrix_rank(X[S + [i]]) == len(S) + 1:
            S.append(int(i))
    return S

rg = np.random.default_rng(3)
peor = 0
for _ in range(40):
    X = rg.integers(-2, 3, size=(8, 4)).astype(float)
    p = rg.integers(1, 20, size=8).astype(float)
    S = base_voraz(X, p)
    mejor = max(p[list(T)].sum() for r in range(5) for T in itertools.combinations(range(8), r) if r == 0 or np.linalg.matrix_rank(X[list(T)]) == r)
    peor = max(peor, mejor - p[S].sum())
print("base de vectores de peso máximo: mayor pérdida del voraz en 40 instancias =", peor)

# ---- más allá de los matroides: cobertura máxima, la función submodular de siempre ----
def cobertura(conjuntos, elegidos):
    return len(set().union(*[conjuntos[i] for i in elegidos])) if elegidos else 0

def voraz_cobertura(conjuntos, k):
    S = []
    for _ in range(k):
        S.append(max((i for i in range(len(conjuntos)) if i not in S), key=lambda i: cobertura(conjuntos, S + [i])))
    return S

rg2 = random.Random(5)
peor_cociente, k = 1.0, 3
for _ in range(250):
    conjuntos = [set(rg2.sample(range(14), rg2.randint(2, 7))) for _ in range(8)]
    opt = max(cobertura(conjuntos, T) for T in itertools.combinations(range(8), k))
    peor_cociente = min(peor_cociente, cobertura(conjuntos, voraz_cobertura(conjuntos, k)) / opt)
print(f"cobertura máxima con k = {k}: peor cociente voraz/óptimo en 250 instancias = {peor_cociente:.3f}   (cota 1 - 1/e = {1 - np.exp(-1):.3f})")

# un caso donde el voraz no es óptimo: el conjunto grande engaña
trampa = [set(range(1, 5)), set(range(5, 9)), {1, 2, 5, 6, 7}]
print("trampa: voraz cubre", cobertura(trampa, voraz_cobertura(trampa, 2)), "elementos, el óptimo cubre", cobertura(trampa, [0, 1]))

Output reports three things: Kruskal agrees with SciPy (zero difference); linear-basis greedy never loses to brute force (a matroid); and in coverage the worst ratio observed on random instances is well above 1−1/e1 - 1/e, but the “trap” confirms no equality: with {1,2,3,4}\{1, 2, 3, 4\}, {5,6,7,8}\{5, 6, 7, 8\} and {1,2,5,6,7}\{1, 2, 5, 6, 7\} greedy first takes the 5-element set and covers 7, while the first two cover 8.

Common mistakes

Exercises

ProofEarliest finish by exchange
Prove: Earliest-finish greedy obtains a maximum-cardinality schedule.
0
This time do not use ‘greedy stays ahead’: prove by induction on nn that an optimum contains greedy's first choice. Let i1i_1 be the earliest-finishing interval, S′S' the intervals starting no earlier than f(i1)f(i_1), and O={j1,…,jm}O = \{j_1, \dots, j_m\} an optimum sorted by finish.

Step 1 of 5. You want to transform OO into an optimum containing i1i_1. What change do you make?

ProofThe Rado–Edmonds converse
Prove: Let (E,I)(E, \mathcal{I}) satisfy (I1) and (I2). If greedy returns a maximum-weight independent set for every w:E→R≥0w : E \to \R_{\ge 0}, then it satisfies (I3).
0
Prove by contrapositive: suppose (I3) fails and construct weights for which greedy fails. Let A,B∈IA, B \in \mathcal{I} with ∣A∣<∣B∣\abs{A} < \abs{B} and A∪{x}∉IA \cup \{x\} \notin \mathcal{I} for every x∈B∖Ax \in B \setminus A. Write q=∣A∖B∣q = \abs{A \setminus B} and r=∣B∖A∣r = \abs{B \setminus A}.

Step 1 of 5. Since ∣A∣<∣B∣\abs{A} < \abs{B}, how are qq and rr related?

QuizWhich are matroids?
Choose all set systems that are matroids.

More than one answer may be correct.

QuizIntervals with values
Each interval now has a value, and you want a compatible set of maximum total value. What is true?
QuizNegative weights and bases
In a matroid with possibly negative weights, how do you obtain a maximum-weight independent set and maximum-weight base greedily?
CodeA noncanonical-system detector
Implement primer_contraejemplo(monedas). It receives a list of coin values (distinct positive integers including 1) and returns the smallest amount xx for which greedy (repeatedly take the largest fitting coin) uses more coins than optimum, or None if the system is canonical. Use dynamic programming for optimum. By the Kozen–Zaks bound, checking amounts below cn−1+cnc_{n-1} + c_n (the two largest coins) suffices when there are at least three coins; with fewer, greedy is always optimal.
def primer_contraejemplo(monedas):
  # menor importe en que el voraz paga con más monedas que el óptimo; None si no hay
  pass
Shift+Enter to run
NumericOptimal maximum lateness
Six tasks with durations t=(3,2,4,1,5,2)t = (3, 2, 4, 1, 5, 2) and deadlines d=(6,5,13,4,11,9)d = (6, 5, 13, 4, 11, 9) run on one machine without interruption or gaps. Calculate maximum lateness L=max⁡jmax⁡(0,fj−dj)L = \max_j \max(0, f_j - d_j) of the best possible order.
NumericBest profit with deadlines
Five unit tasks have (deadline, profit) (2,100)(2, 100), (1,19)(1, 19), (2,27)(2, 27), (1,25)(1, 25) and (3,15)(3, 15). Profit is earned only when a task finishes on time. What is maximum total profit?
NumericBases of a graphic matroid
How many bases does the graphic matroid of complete graph K4K_4 (4 vertices, 6 edges) have?

Summary

Key idea
A greedy algorithm is correct when one can prove that staying ahead each step (or exchanging an optimum until it resembles greedy) never loses. Matroids are exactly set systems where weight-greedy works for all weights: augmentation is both cause and characterization.
  • Greedy = local choice without backtracking. Counterexamples refute; stays-ahead or exchange proves. Always look for counterexamples before trusting greedy.
  • Intervals. Earliest finish maximizes compatible request count; assigning rooms by start grows to depth, an attained lower bound.
  • Maximum lateness. Earliest deadline is optimal: swap adjacent inversions and maximum lateness never rises. Shortest first and least slack fail.
  • Knapsack and Huffman. Density-greedy is optimal for fractional knapsack and fails for 0/1. In Huffman an exchange lemma makes the two least frequent deepest siblings.
  • Matroid: (I1) empty, (I2) heredity, (I3) augmentation. Graphic (forests), linear, uniform, partition and unit deadline tasks are matroids; matchings, independent vertex sets and knapsack are not. All bases have equal size.
  • Rado and Edmonds. On a system with (I1) and (I2), weight-greedy is optimal for every w≥0w \ge 0 if and only if (I3) holds. Kruskal is the graphic-matroid case.
  • Beyond. On the intersection of two matroids or with submodular functions, greedy only approximates (1/21/2 and 1−1/e1 - 1/e): do not confuse it with exact matroid greedy.