A greedy algorithm makes the choice that looks best RIGHT NOW and never revisits it. No backtracking, no memo table, one pass, usually after a sort. That's the appeal: greedy solutions are short, fast (often O(n log n) dominated by the sort), and easy to implement. That's also the danger: greedy is only correct when local optimum ⇒ global optimum, and that's a THEOREM you must be able to argue, not an assumption you get to make.
The standard justification is the exchange argument: show that any optimal solution can be transformed into the greedy one without getting worse, so the greedy solution is at least as good. When that argument holds (interval scheduling: picking the earliest-finishing meeting never hurts), greedy is optimal. When it fails (coin change with coins {1, 3, 4}: greedy takes 4+1+1 = 3 coins for 6, but 3+3 = 2 coins), you need dynamic programming instead.
Classic greedy win: maximum non-overlapping intervals
// Attend the maximum number of meetings (one room).
// Greedy rule: always take the meeting that ENDS earliest.
function maxMeetings(intervals) {
const sorted = [...intervals].sort((a, b) => a[1] - b[1]); // by END time
let count = 0;
let lastEnd = -Infinity;
for (const [start, end] of sorted) {
if (start >= lastEnd) { // compatible with everything chosen so far
count++;
lastEnd = end; // commit, never un-choose
}
}
return count;
}
// Why earliest-end? Any optimal schedule's FIRST meeting can be swapped
// for the earliest-ending one without blocking later meetings. Greedy stays optimal.The greedy checklist
- 1
Sort into a decision order
Almost every greedy solution starts with a sort that makes "locally best" well-defined: by end time, by ratio, by deadline.
- 2
Define the local rule
One sentence: "take the earliest end / the largest ratio / the k smallest". If your rule needs a paragraph, it's probably DP.
- 3
Commit without regret
Greedy never revisits. If the solution structure requires un-choosing, it's backtracking or DP.
- 4
Argue the exchange
Can any optimal answer be rearranged to match your choice without loss? If yes, implement. If no, find a counterexample or switch to DP.