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
  1. The idea
  2. How to recognise it
  3. When not to use it
  4. Template
  5. Complexity
  6. Worked examples
  7. Pitfalls
  8. Practise it
  9. Learn the foundations
  10. References

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:

Learn the foundations

Related patterns

References

dsa.pattern.greedy-with-sorting · version 1