Greedy
Signal: optimization where a local rule looks like it should work: pick the earliest-ending, the farthest-reaching, the cheapest-so-far, or reset when a running total turns negative. Often O(n) or O(n log n) with sorting.
Core idea: make the locally best choice at every step and never revisit it. The hard part is proving that's safe. Two standard arguments:
- Exchange argument: take any optimal solution; show you can swap its first choice for the greedy choice without making it worse.
- Stays-ahead argument: show that after every step, greedy is at least as good as any other strategy (e.g., it has reached at least as far).
Greedy is often wrong
Coin change with coins [1, 5, 6, 9] and amount 11: greedy takes 9+1+1 (3 coins), but 5+6 (2 coins) is optimal, so you need DP. If you can't argue why greedy works, test it against small brute-force cases before committing.
Kadane's algorithm: greedy meets DP
The best subarray ending at i either extends the best one ending at i−1 or starts fresh at i:
python
best = cur = nums[0]
for x in nums[1:]:
cur = max(x, cur + x) # a negative running sum only hurts: drop it
best = max(best, cur)