Greedy Algorithms
Make the locally best choice at every step — when that provably works, how to prove it, and when it fails.
A greedy algorithm builds a solution step by step, always taking the choice that looks best right now, and never reconsidering. When it works, it's usually the simplest and fastest solution — often just "sort, then scan".
The catch: greedy is correct only when the problem has
- Greedy-choice property — some optimal solution starts with the greedy choice, and
- Optimal substructure — after making it, what remains is a smaller instance of the same problem.
When greedy fails
Coin change with coins {1, 3, 4} and target 6: greedy takes 4 + 1 + 1 (3 coins), but 3 + 3 (2 coins) is optimal. For arbitrary coin systems you need DP. (For "canonical" systems like US coins, greedy happens to be optimal.)
Proving greedy correct: the exchange argument
Take any optimal solution that differs from the greedy one. Show you can swap in the greedy choice without making it worse. Repeating the swap transforms the optimal solution into the greedy one, so greedy is optimal too.
Classic 1: activity selection (interval scheduling)
Choose the maximum number of non-overlapping meetings. Greedy rule: always pick the meeting that ends earliest. It leaves the most room for the rest (exchange argument: replacing the optimum's first meeting with the earliest-ending one can't cause a conflict).
int maxMeetings(int[][] intervals) {
Arrays.sort(intervals, (a, b) -> Integer.compare(a[1], b[1])); // by end time
int count = 0, lastEnd = Integer.MIN_VALUE;
for (int[] iv : intervals) {
if (iv[0] >= lastEnd) { // doesn't overlap the last chosen one
count++;
lastEnd = iv[1];
}
}
return count;
}
// "Minimum removals to make intervals non-overlapping" = n - maxMeetingsdef max_meetings(intervals):
intervals.sort(key=lambda iv: iv[1]) # by end time
count, last_end = 0, float("-inf")
for start, end in intervals:
if start >= last_end:
count += 1
last_end = end
return countfunction maxMeetings(intervals: [number, number][]): number {
intervals.sort((a, b) => a[1] - b[1]); // by end time
let count = 0, lastEnd = -Infinity;
for (const [s, e] of intervals) {
if (s >= lastEnd) { count++; lastEnd = e; }
}
return count;
}Classic 2: jump game
Can you reach the last index if a[i] is the max jump from i? Track the farthest reachable index while scanning; if you ever stand beyond it, you're stuck.
boolean canJump(int[] a) {
int far = 0;
for (int i = 0; i < a.length; i++) {
if (i > far) return false;
far = Math.max(far, i + a[i]);
}
return true;
}def can_jump(a):
far = 0
for i, x in enumerate(a):
if i > far:
return False
far = max(far, i + x)
return Truefunction canJump(a: number[]): boolean {
let far = 0;
for (let i = 0; i < a.length; i++) {
if (i > far) return false;
far = Math.max(far, i + a[i]);
}
return true;
}Classic 3: Huffman coding
Build an optimal prefix-free code for compression: repeatedly merge the two least frequent symbols into a new node (using a min-heap). Frequent symbols end up near the root with short codes. Used inside DEFLATE (zip, gzip, PNG) and JPEG.
More greedy algorithms you'll meet
| Problem | Greedy rule | Lesson |
|---|---|---|
| Fractional knapsack | Highest value/weight first (0/1 knapsack needs DP) | Knapsack DP |
| Minimum spanning tree | Cheapest safe edge (Kruskal) / closest vertex (Prim) | MST |
| Dijkstra | Closest unvisited vertex | Shortest paths |
| Gas station | Restart after a negative running tank | Greedy pattern |
| Task scheduler | Schedule the most frequent task first | Greedy pattern |
| Minimum platforms / meeting rooms | Sweep sorted start/end events | Merge intervals |
- Greedy takes the locally best choice and never backtracks.
- It's correct only with the greedy-choice property and optimal substructure — prove it (exchange argument) or find a counterexample.
- Most greedy solutions are "sort by the right key, then scan": O(n log n).
- If greedy fails, the problem usually needs dynamic programming.
QMinimum number of arrows to burst all balloons (intervals).medium
Sort by end. Shoot an arrow at the first balloon's end; it bursts every balloon starting at or before that point. Move to the next balloon starting after it and repeat. Same proof as activity selection.
QWhy does greedy work for fractional knapsack but not 0/1 knapsack?medium
With fractions, you can always fill the remaining capacity with the best value-per-weight item, so the exchange argument holds. In 0/1 knapsack an item is all-or-nothing: taking the best-ratio item can waste capacity that a different combination would fill better. That requires DP.