Introduction

A greedy algorithm builds a solution one choice at a time. At every step it picks the option that looks best right now, never undoing that choice later. The hope is that a sequence of locally optimal choices produces a globally optimal answer.

Greedy methods are often short and run in near-linear time once the input is sorted, but they are not a universal recipe. The same style of choice that works for activity selection fails for the 0/1 knapsack problem; the right tool there is dynamic programming. This note states when the greedy method is sound, proves the classical activity-selection algorithm, and lists the other GATE syllabus algorithms that are greedy under the hood.

Prerequisites

  • Asymptotic Notation: OO, Θ\Theta and Ω\Omega for the running times below.
  • Sorting a list of nn numbers in O(nlg⁡n)O(n \lg n) time (a suitable comparison sort such as merge sort or heapsort).

Core concepts

The greedy pattern

  1. Cast the problem so that a solution is a sequence of choices.
  2. Prove that some choice made by a fixed rule (the greedy choice) belongs to an optimal solution (greedy-choice property).
  3. Prove that after that choice the remaining problem is an instance of the same form (optimal substructure).
  4. Implement the rule: often a sort followed by a single left-to-right scan.

Dynamic programming also needs optimal substructure, but it considers every feasible choice at a subproblem. Greedy commits to one choice and never revisits it. That is why greedy code is usually faster when it works, and why a missing proof is dangerous.

When greedy works, and when it does not

ProblemGreedy ruleOptimal?
Activity selection (max number of non-overlapping intervals)earliest finish timeyes
Fractional knapsackhighest value/weight firstyes
0/1 knapsackhighest value/weight firstno
Huffman codingmerge the two least frequent symbolsyes
MST (Kruskal, Prim)lightest safe edgeyes
Dijkstra (non-negative weights)extract the unsettled vertex of least distanceyes
Coin change with arbitrary denominationslargest coin firstno (counterexample: coins 1, 3, 4 and amount 6)

Greedy versus dynamic programming. Both need optimal substructure. Greedy needs the stronger greedy-choice property so that one locally best option is always safe. If that property fails, DP (or another method) is required.

The exchange argument

Most greedy proofs, including every proof in this note and in Huffman Coding and Optimal Merge Patterns, follow one template.

  1. Let G=(g1,g2,…)G = (g_1, g_2, \ldots) be the greedy solution and OO an optimal solution that agrees with GG on as many leading choices as possible.
  2. Suppose they first differ at choice kk: greedy picked gkg_k, OO picked some ok≠gko_k \ne g_k.
  3. Exchange: replace oko_k by gkg_k in OO. Show that the result is still feasible and no worse.
  4. The modified solution is optimal and agrees with GG on kk choices, contradicting the choice of OO. Hence GG itself is optimal.

The whole proof rests on step 3. When a proposed rule fails, it is step 3 that breaks, and the failure usually points straight to a counterexample.

Algorithms and pseudocode

Pseudocode uses 1-based arrays, <- for assignment and A[i..j] for the subarray from position ii to position jj.

Activity selection

Input. nn activities a1,…,ana_1, \ldots, a_n, each with a start time sis_i and a finish time fif_i, already sorted so that f1≤f2≤⋯≤fnf_1 \le f_2 \le \cdots \le f_n.

Output. A largest set of mutually compatible activities (no two overlap: aia_i and aja_j with i<ji < j are compatible when fi≤sjf_i \le s_j).

The displayed procedure assumes n>=1; an empty-input wrapper returns the empty set when n=0, before accessing a_1.

Text
GREEDY-ACTIVITY-SELECTOR(s, f, n)
1  A <- {a_1}
2  k <- 1
3  for m <- 2 to n
4      if s[m] >= f[k] then
5          A <- A union {a_m}
6          k <- m
7  return A

Best / average / worst time. Θ(n)\Theta(n) after the O(nlg⁡n)O(n \lg n) sort that puts finish times in order. Space Θ(1)\Theta(1) beyond the output set (or Θ(n)\Theta(n) if the set is materialised).

Edge cases. n=0n = 0 returns the empty set; n=1n = 1 returns {a1}\{a_1\}. Activities that touch at an endpoint (fi=sjf_i = s_j) are treated as compatible, matching the usual GATE convention; if a problem forbids touching, change the test to s[m] > f[k].

Fractional knapsack

Input. nn items with weights wi>0w_i > 0 and values vi≥0v_i \ge 0, and a capacity WW. Any fraction of an item may be taken.

Greedy rule. Sort by density vi/wiv_i / w_i descending. Fill the knapsack from the densest item; take a fraction of the first item that does not fit wholly.

Text
FRACTIONAL-KNAPSACK(v, w, W, n)
1  sort items so that v[1]/w[1] >= ... >= v[n]/w[n]
2  value <- 0;  rem <- W
3  for i <- 1 to n
4      if w[i] <= rem then
5          value <- value + v[i]
6          rem <- rem - w[i]
7      else
8          value <- value + v[i] * (rem / w[i])
9          return value
10 return value

Cost model and cases. Assume n≥0n\ge0, W≥0W\ge0, constant-time arithmetic, density comparisons and indexed accesses, and mutable item records. After sorting, for n≥1n\ge1 the scan takes Θ(1)\Theta(1) best time (the first item exceeds the remaining capacity) and Θ(n)\Theta(n) worst time; its average needs a distribution of weights and capacity. Empty input takes Θ(1)\Theta(1). The scan uses O(1)O(1) auxiliary words and returns one scalar; storing a fraction for every item would instead require Θ(n)\Theta(n) output words. Sort time and workspace are additional: for example, standard nonadaptive bottom-up mergesort takes Θ(nlg⁡(n+1))\Theta(n\lg(n+1)) time and Θ(n)\Theta(n) scratch words in best, average and worst cases for n≥1n\ge1, excluding the input and scalar output (constant for empty input). An in-place sort has its own workspace bound. The 0/1 version (an item is taken whole or not at all) is not solved by this rule; see DP: 0/1 Knapsack and Matrix-Chain.

Interval-graph colouring (lecture halls)

Related material. Scheduling every activity into as few rooms as possible is the interval-colouring problem. Sort all 2n2n endpoints by time, with finishes before starts at equal times (touching intervals are compatible); scan left to right, opening a room at each start and freeing one at each finish, and track the peak active count. The number of rooms needed equals the maximum depth (how many activities are live at once). Time O(nlg⁡n)O(n \lg n). It belongs with activity selection but is not a separate syllabus item.

Mathematical explanation

Greedy-choice property for activity selection

Claim. There exists an optimal solution that contains the activity a1a_1 of earliest finish time.

Proof. Let AA be any optimal solution and let aja_j be the activity in AA of earliest finish time. If aj=a1a_j = a_1 we are done. Otherwise replace aja_j by a1a_1. Because f1≤fjf_1 \le f_j, activity a1a_1 finishes no later than aja_j and therefore conflicts with no activity of A∖{aj}A \setminus \{a_j\} that aja_j did not already conflict with. The new set has the same size and is feasible, so it is optimal and contains a1a_1.

Optimal substructure

After choosing a1a_1, every remaining feasible activity starts at or after f1f_1. The problem on that subset is again an activity-selection instance. An optimal solution for the original problem is {a1}\{a_1\} union an optimal solution of the residual instance. The inductive combination of the greedy-choice property and optimal substructure proves that GREEDY-ACTIVITY-SELECTOR returns an optimal set (CLRS 3e, Section 16.1).

Fractional knapsack correctness (sketch)

Suppose an optimal packing takes a smaller fraction of a denser item ii than of a less dense item jj. Transferring weight from jj to ii cannot decrease the total value, and eventually yields a packing that fills denser items first. Hence some optimal packing agrees with the greedy order.

Worked examples

Activity selection on six activities

Activities sorted by finish time:

ii123456
sis_i130585
fif_i456799
  • Start with A={a1}A = \{a_1\}, k=1k = 1.
  • m=2m = 2: s2=3<4=f1s_2 = 3 < 4 = f_1, skip.
  • m=3m = 3: s3=0<4s_3 = 0 < 4, skip.
  • m=4m = 4: s4=5≥4s_4 = 5 \ge 4, take a4a_4, set k=4k = 4.
  • m=5m = 5: s5=8≥7s_5 = 8 \ge 7, take a5a_5, set k=5k = 5.
  • m=6m = 6: s6=5<9s_6 = 5 < 9, skip.

Result A={a1,a4,a5}A = \{a_1, a_4, a_5\}, size 3. Checking all 26=642^6 = 64 subsets confirms that no compatible set has 4 activities. The optimum is not unique: {a2,a4,a5}\{a_2, a_4, a_5\} is the only other compatible set of size 3. Greedy returns one optimal set, not all of them.

Activity selection timeline for six activities
Figure 1. Timeline of the six activities sorted by finish time: the greedy scan keeps a1a_1, a4a_4 and a5a_5 (shaded) and rejects a2a_2, a3a_3 and a6a_6 because each overlaps the latest kept activity.

Fractional knapsack

Items (v,w)(v, w): (60,10)(60, 10), (100,20)(100, 20), (120,30)(120, 30); capacity W=50W = 50. Densities 66, 55, 44. Take all of the first two items (weight 30, value 160) and 20/3020/30 of the third (value 80). Total value 240240. The 0/1 optimum on the same instance is only 220220 (items 2 and 3), so the fractional and 0/1 answers differ.

Coin-change counterexample

Coins {1,3,4}\{1, 3, 4\}, amount 6. Largest-first greedy takes 4+1+14 + 1 + 1 (three coins). Optimal is 3+33 + 3 (two coins). Greedy fails because the denominations are not a canonical coin system.

Job sequencing with deadlines

Each of nn jobs takes one unit of time, has a deadline did_i (it must finish by time did_i) and earns profit pip_i only if it meets its deadline. One job runs at a time. Greedy rule: consider jobs in decreasing order of profit, and place each one in the latest free unit slot t≤dit \le d_i; if no such slot is free, reject it. A set of jobs is feasible exactly when, for every tt, at most tt of its jobs have deadline ≤t\le t. This structure is what makes the exchange argument work.

JobJ1J_1J2J_2J3J_3J4J_4J5J_5J6J_6J7J_7
Profit pip_i3530252015125
Deadline did_i3442312
  • J1J_1: slot 3. J2J_2: slot 4. J3J_3: slot 4 is taken and slot 3 is taken, so slot 2. J4J_4: slot 2 is taken, so slot 1.
  • J5J_5 (d=3d=3), J6J_6 (d=1d=1) and J7J_7 (d=2d=2) find every slot up to their deadline full, so all three are rejected.

Schedule by time slot: J4,J3,J1,J2J_4, J_3, J_1, J_2, total profit 20+25+35+30=11020+25+35+30 = 110. Checking all 272^7 subsets confirms 110 is the maximum. The simple slot search costs O(n2)O(n^2) in the worst case after an O(nlg⁡n)O(n \lg n) sort. With a disjoint-set structure that points every slot to the latest free slot at or before it, the search drops to near-linear time.

Placing a job in the latest free slot, not the earliest, is essential. Earliest-slot placement can block a later job with a tight deadline: with profits 10 and 9 and deadlines 2 and 1, earliest-slot placement puts the first job in slot 1 and loses the second (profit 10), while latest-slot placement keeps both (profit 19).

Coin systems: when largest-first is safe

A coin system is canonical when largest-coin-first gives the fewest coins for every amount. Exhaustive checks up to amount 2000 give:

DenominationsGreedy always optimal?Smallest failing amount
1, 2, 5, 10, 20, 50, 100, 200, 500yesnone
1, 5, 10, 25yesnone
1, 3, 4no6 (greedy 4+1+14+1+1, optimum 3+33+3)
1, 7, 10no14 (greedy 10+1+1+1+110+1+1+1+1, five coins; optimum 7+77+7)

EDGE CASE. Without a coin of value 1, largest-first may find no answer when one exists. With coins {3,5}\{3, 5\} and amount 9, greedy takes 5, then 3, leaves 1 and is stuck, but 3+3+33+3+3 works. The reliable method for any coin system is the dynamic program c(a)=1+min⁡d≤ac(a−d)c(a) = 1 + \min_{d \le a} c(a-d), which costs O(ka)O(ka) for kk denominations and amount aa. That is pseudo-polynomial, as explained in Dynamic Programming Fundamentals.

Important properties and observations

  • Sorting by finish time is essential for activity selection. Other rules fail on three intervals:
RuleInstanceRule picksOptimum
Earliest start[1,10],[2,3],[4,5][1,10], [2,3], [4,5][1,10][1,10] only2: [2,3],[4,5][2,3], [4,5]
Shortest duration[1,9],[8,11],[10,20][1,9], [8,11], [10,20][8,11][8,11] only2: [1,9],[10,20][1,9], [10,20]
  • Weighted activities are different. If each activity carries a weight and the goal is maximum total weight, earliest finish fails: with [0,3][0,3] and [4,6][4,6] of weight 1 each and [0,10][0,10] of weight 10, greedy collects weight 2 but the optimum is 10. Weighted interval scheduling needs dynamic programming.
  • In fractional knapsack, at most one item is taken fractionally: the first item that does not fit.
  • The greedy choice must be proved, not assumed from a similar-looking problem.
  • Many syllabus algorithms are greedy once recognised: Huffman coding, Kruskal, Prim, and Dijkstra (non-negative weights). Their proofs reuse the same two ingredients: a safe local choice and a residual subproblem of the same form.
  • Greedy algorithms that only need a sort and a scan are O(nlg⁡n)O(n \lg n); the constant factors are small and the code is short.

Common misconceptions.

  • "Greedy always works for optimisation." False: 0/1 knapsack and arbitrary coin systems are counterexamples.
  • "The earliest-start rule selects the most activities." Counterexample: [1,10],[2,3],[4,5][1, 10], [2, 3], [4, 5] yields one activity under earliest start and two under earliest finish.
  • "Fractional and 0/1 knapsack share an algorithm." Only the fractional version is greedy; 0/1 needs DP.

GATE examination perspective

  • PROVE OR DISPROVE. A one-line counterexample beats a vague claim that a greedy rule "usually works".
  • EARLIEST FINISH, NOT EARLIEST START. Activity selection uses finish times; mixing the two is a common pitfall.
  • TOUCHING INTERVALS. Check whether fi=sjf_i = s_j counts as a conflict in the question statement.
  • FRACTIONAL VERSUS 0/1. If items cannot be split, density order is not safe.
  • JOB SEQUENCING. Sort by profit, then place each job in the latest free slot not after its deadline. Expect questions on the maximum profit or on which jobs are rejected.
  • COIN SYSTEMS. Largest-first is safe only for canonical systems. Test a small amount like 6 for {1,3,4}\{1,3,4\} or 14 for {1,7,10}\{1,7,10\} before trusting it. Without a 1-coin, greedy may find no answer at all.
  • WEIGHTS CHANGE THE ANSWER. Earliest finish maximises the number of activities, not their total weight.
  • RECOGNISE THE PATTERN. For Huffman, MST and Dijkstra, name the greedy choice and the data structure that implements it (heap, Union-Find).

Summary

Sources

  1. T. H. Cormen, C. E. Leiserson, R. L. Rivest, C. Stein, Introduction to Algorithms, 3rd ed., MIT Press, 2009: Chapter 16, Section 16.1 (activity selection) and Section 16.2 (elements of the greedy strategy).

Next steps