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: , and for the running times below.
- Sorting a list of numbers in time (a suitable comparison sort such as merge sort or heapsort).
Core concepts
The greedy pattern
- Cast the problem so that a solution is a sequence of choices.
- Prove that some choice made by a fixed rule (the greedy choice) belongs to an optimal solution (greedy-choice property).
- Prove that after that choice the remaining problem is an instance of the same form (optimal substructure).
- 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
| Problem | Greedy rule | Optimal? |
|---|---|---|
| Activity selection (max number of non-overlapping intervals) | earliest finish time | yes |
| Fractional knapsack | highest value/weight first | yes |
| 0/1 knapsack | highest value/weight first | no |
| Huffman coding | merge the two least frequent symbols | yes |
| MST (Kruskal, Prim) | lightest safe edge | yes |
| Dijkstra (non-negative weights) | extract the unsettled vertex of least distance | yes |
| Coin change with arbitrary denominations | largest coin first | no (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.
- Let be the greedy solution and an optimal solution that agrees with on as many leading choices as possible.
- Suppose they first differ at choice : greedy picked , picked some .
- Exchange: replace by in . Show that the result is still feasible and no worse.
- The modified solution is optimal and agrees with on choices, contradicting the choice of . Hence 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 to position .
Activity selection
Input. activities , each with a start time and a finish time , already sorted so that .
Output. A largest set of mutually compatible activities (no two overlap: and with are compatible when ).
The displayed procedure assumes n>=1; an empty-input wrapper returns the empty set when n=0, before accessing a_1.
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 ABest / average / worst time. after the sort that puts finish times in order. Space beyond the output set (or if the set is materialised).
Edge cases. returns the empty set; returns . Activities that touch at an endpoint () 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. items with weights and values , and a capacity . Any fraction of an item may be taken.
Greedy rule. Sort by density descending. Fill the knapsack from the densest item; take a fraction of the first item that does not fit wholly.
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 valueCost model and cases. Assume , , constant-time arithmetic, density comparisons and indexed accesses, and mutable item records. After sorting, for the scan takes best time (the first item exceeds the remaining capacity) and worst time; its average needs a distribution of weights and capacity. Empty input takes . The scan uses auxiliary words and returns one scalar; storing a fraction for every item would instead require output words. Sort time and workspace are additional: for example, standard nonadaptive bottom-up mergesort takes time and scratch words in best, average and worst cases for , 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 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 . 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 of earliest finish time.
Proof. Let be any optimal solution and let be the activity in of earliest finish time. If we are done. Otherwise replace by . Because , activity finishes no later than and therefore conflicts with no activity of that did not already conflict with. The new set has the same size and is feasible, so it is optimal and contains .
Optimal substructure
After choosing , every remaining feasible activity starts at or after . The problem on that subset is again an activity-selection instance. An optimal solution for the original problem is 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 than of a less dense item . Transferring weight from to 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:
| 1 | 2 | 3 | 4 | 5 | 6 | |
|---|---|---|---|---|---|---|
| 1 | 3 | 0 | 5 | 8 | 5 | |
| 4 | 5 | 6 | 7 | 9 | 9 |
- Start with , .
- : , skip.
- : , skip.
- : , take , set .
- : , take , set .
- : , skip.
Result , size 3. Checking all subsets confirms that no compatible set has 4 activities. The optimum is not unique: is the only other compatible set of size 3. Greedy returns one optimal set, not all of them.

Fractional knapsack
Items : , , ; capacity . Densities , , . Take all of the first two items (weight 30, value 160) and of the third (value 80). Total value . The 0/1 optimum on the same instance is only (items 2 and 3), so the fractional and 0/1 answers differ.
Coin-change counterexample
Coins , amount 6. Largest-first greedy takes (three coins). Optimal is (two coins). Greedy fails because the denominations are not a canonical coin system.
Job sequencing with deadlines
Each of jobs takes one unit of time, has a deadline (it must finish by time ) and earns profit 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 ; if no such slot is free, reject it. A set of jobs is feasible exactly when, for every , at most of its jobs have deadline . This structure is what makes the exchange argument work.
| Job | |||||||
|---|---|---|---|---|---|---|---|
| Profit | 35 | 30 | 25 | 20 | 15 | 12 | 5 |
| Deadline | 3 | 4 | 4 | 2 | 3 | 1 | 2 |
- : slot 3. : slot 4. : slot 4 is taken and slot 3 is taken, so slot 2. : slot 2 is taken, so slot 1.
- (), () and () find every slot up to their deadline full, so all three are rejected.
Schedule by time slot: , total profit . Checking all subsets confirms 110 is the maximum. The simple slot search costs in the worst case after an 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:
| Denominations | Greedy always optimal? | Smallest failing amount |
|---|---|---|
| 1, 2, 5, 10, 20, 50, 100, 200, 500 | yes | none |
| 1, 5, 10, 25 | yes | none |
| 1, 3, 4 | no | 6 (greedy , optimum ) |
| 1, 7, 10 | no | 14 (greedy , five coins; optimum ) |
EDGE CASE. Without a coin of value 1, largest-first may find no answer when one exists. With coins and amount 9, greedy takes 5, then 3, leaves 1 and is stuck, but works. The reliable method for any coin system is the dynamic program , which costs for denominations and amount . 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:
| Rule | Instance | Rule picks | Optimum |
|---|---|---|---|
| Earliest start | only | 2: | |
| Shortest duration | only | 2: |
- Weighted activities are different. If each activity carries a weight and the goal is maximum total weight, earliest finish fails: with and of weight 1 each and 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 ; 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: 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 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 or 14 for 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
- 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).