Greedy: take the best local choice and never look back
A greedy algorithm makes the best-looking choice at every step and is never undone. When it's correct, how to argue it, and how to tell it apart from DP.
In short
Greedy picks the locally best option at each step and never reconsiders. It's fast (often one pass, or a sort plus one pass) but only correct when a local choice is provably safe. If a small counterexample breaks it, use DP.
The idea: one number is enough
Jump game: each cell says how far you can jump from it; can you reach the last cell? You don't need to explore paths. Track one number: the farthest index reachable so far. If you ever stand beyond it, you're stuck; otherwise update it with i + nums[i].
1def can_jump(nums):2 reach = 03 for i, step in enumerate(nums):4 if i > reach:5 return False6 reach = max(reach, i + step)7 return True
Variables
Greedy or DP?
Greedy works when…
- A local best choice is part of some optimal answer
- You can swap any optimal solution into the greedy one (exchange argument)
- Typical: interval scheduling, jump game, gas station, assigning cookies
Use DP when…
- A small counterexample breaks the greedy choice
- Coins 1, 3, 4 and amount 6: greedy gives 3 coins, optimal is 2
- You need to compare several options, not just pick one
The classic: max non-overlapping meetings
To fit the most meetings in one room, sort by end time and keep each meeting that starts after the last chosen one ends. Why end time? A meeting that finishes earliest leaves the most room for the rest. Sorting by start time or by duration both have counterexamples.
intervals.sort(key=lambda m: m[1]) # by end time
last_end, count = -inf, 0
for start, end in intervals:
if start >= last_end:
count += 1
last_end = endKey takeaways
- 01Greedy = best local choice, never reconsidered.
- 02Look for a sort or a single running value that makes the choice obvious.
- 03Always try a tiny counterexample; if it breaks, switch to DP.
- 04Cost is usually O(n) or O(n log n) because of the sort.
Check your understanding
1 of 3
What does a greedy algorithm do?
Related topics
1D dynamic programming
If a recursive solution solves the same subproblem many times, store each answer once. Define dp[i] (what it means), write how it depends on smaller entries, fill it from the base case up. Time = number of states × work per state.
10 min read →Intervals
Sort by start, then walk once. An interval either overlaps the last one (extend its end with `max`) or starts a new group. Cost: O(n log n) for the sort, O(n) for the sweep.
7 min read →Priority queues
A heap keeps the smallest (min-heap) or largest (max-heap) item at the root, and every parent is ≤ its children. Reading the top is O(1); push and pop are O(log n). It's the data structure behind a priority queue.
8 min read →