Optimization · Advanced
Greedy choice after sorting
Order the candidates so the locally best choice is safe, then commit to it; an exchange argument, not intuition, proves the greedy answer optimal.
On this page
The idea
A greedy algorithm makes one irrevocable choice per step. It is correct only if some optimal solution agrees with that choice, which you show with an exchange argument: take any optimal solution, swap its first differing choice for the greedy one, and show the result is still optimal.
Sorting is usually what makes the choice cheap: by end time for scheduling, by ratio for fractional knapsack, by deadline for lateness. A single pass that keeps a running best (cheapest price so far, tallest wall so far) is the same idea without the sort.
How to recognise it
- "Maximum number of non-overlapping", "minimum number of", "earliest finish", "cheapest so far".
- A natural ordering of the items makes each decision local.
- Constraints rule out dynamic programming over all subsets.
When not to use it
- You cannot find an exchange argument, or a small counterexample breaks the greedy rule (coin change with arbitrary denominations, 0-1 knapsack): use dynamic programming.
- The choice depends on future items you have not seen and cannot sort by.
Template
Language-neutral pseudocode (Python-like). Adapt names and types to your language; the solved problems below have tested implementations in C#, Python, Java and C++.
# Maximum number of non-overlapping intervals
sort intervals by end
count = 0; last_end = -infinity
for (s, e) in intervals:
if s >= last_end: # compatible with everything chosen so far
count += 1
last_end = e # earliest possible finish leaves the most room
return count
# Running best without sorting (single pass)
best_so_far = first item
for x in rest: answer = combine(answer, x, best_so_far); best_so_far = better(best_so_far, x)- Write the exchange argument before the code; if you cannot, try to break the rule with a three-item example.
Complexity
Time O(n log n), extra space O(1) to O(n). Sorting dominates. The single-pass running-best variant is O(n) time and O(1) extra space.
Worked examples
Buy once, sell once on prices [7, 2, 5, 1, 4]
Track the cheapest price so far. Day 2: cheapest 2. Day 3: profit 5 − 2 = 3. Day 4: cheapest becomes 1. Day 5: profit 4 − 1 = 3. Best profit 3; selling on any day only ever needs the cheapest earlier day.
Pitfalls
- Trusting a greedy rule because it works on the examples.
- Sorting by the wrong key (start instead of end for maximum non-overlapping intervals).
- Breaking ties carelessly when ties affect feasibility.
Practise it
Solved problems with hints, a correctness argument and four tested implementations:
- ProblemBuy once, sell once, profit most· beginner · O(n)
- ProblemTwo walls that hold the most water· intermediate · O(n)
- ProblemCan you hop to the last stone?· intermediate · O(n)
- ProblemWhere to start a round trip on a fuel budget· intermediate · O(n)
- ProblemCombine overlapping bookings· intermediate · O(n log n)
- ProblemHow many rooms for these meetings?· intermediate · O(n log n)
Learn the foundations
Lessons
- ModuleM30 Greedy· advanced
- ModuleM13 Sorting· intermediate
- VisualizerMerge sort· Θ(n log n)
- VisualizerInsertion sort· O(n²) worst, O(n) sorted
- Complexity exerciseSort once, then binary search n times· Θ(n log n)
Related patterns
- PatternSort and merge intervals· O(n log n)
- PatternDynamic programming (1D and 2D)· O(states × transitions)
- PatternTop K with a heap· O(n log k)
References
dsa.pattern.greedy-with-sorting · version 1