Greedy Algorithms
The greedy idea
At each step, make the choice that looks best right now, without reconsidering. It's simple and fast, but only correct for some problems.
When greedy works
You need to be able to argue that a locally best choice never ruins the overall answer (the greedy-choice property). Often the trick is to sort first.
Classic greedy problems
| Problem | Greedy choice |
|---|---|
| Activity selection / meeting rooms | pick the meeting that ends earliest |
| Merge overlapping intervals | sort by start, then extend or close the current interval |
| Jump game | track the furthest index you can reach |
| Coin change with normal coins (1, 5, 10, 25) | always take the largest coin |
| Huffman coding (compression) | merge the two least-frequent symbols |
| Dijkstra / Prim's / Kruskal's | always expand the cheapest option |
When greedy fails ⚠️
Coins [1, 3, 4] for amount 6: greedy takes 4 + 1 + 1 (3 coins), but 3 + 3 (2 coins) is better. That needs DP.
Greedy vs DP
| Greedy | Dynamic programming |
|---|---|
| one choice per step, never revisited | considers every option, keeps the best |
| usually O(n) or O(n log n) | usually bigger |
| needs a proof that it's correct | correct whenever the recurrence is |
💡 Try a few small examples by hand. If greedy gives a wrong answer even once, switch to DP.
Example
def max_meetings(meetings): # (start, end)
count, last_end = 0, float("-inf")
for start, end in sorted(meetings, key=lambda m: m[1]):
if start >= last_end:
count += 1
last_end = end
return count
def merge_intervals(intervals):
merged = []
for start, end in sorted(intervals):
if merged and start <= merged[-1][1]:
merged[-1][1] = max(merged[-1][1], end)
else:
merged.append([start, end])
return merged
def can_jump(nums):
reach = 0
for i, step in enumerate(nums):
if i > reach:
return False
reach = max(reach, i + step)
return True
print(max_meetings([(1, 3), (2, 4), (3, 5), (0, 6), (5, 7)])) # 3
print(merge_intervals([[1, 3], [8, 10], [2, 6], [15, 18]])) # [[1, 6], [8, 10], [15, 18]]
print(can_jump([2, 3, 1, 1, 4]), can_jump([3, 2, 1, 0, 4])) # True False