sagelearnai

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)

Problems

  1. Maximum Subarray (Medium): Kadane: extend or restart
  2. Jump Game (Medium): Track the farthest reachable index
  3. Jump Game II (Medium): Implicit BFS by levels: each jump extends the frontier
  4. Gas Station (Medium): If total gas ≥ total cost, start after the last failure point
  5. Hand of Straights (Medium): The smallest remaining card must start a group; consume consecutive cards from a counter
  6. Merge Triplets to Form Target Triplet (Medium): Ignore any triplet exceeding target anywhere; the rest must cover each target coordinate
  7. Partition Labels (Medium): Record last occurrence; extend the current part's end; cut when i reaches it
  8. Valid Parenthesis String (Medium): Track the range [lo, hi] of possible open counts
  9. Candy (Hard): Two passes: left-to-right for left neighbors, right-to-left for right neighbors, take max
  10. Assign Cookies (Easy): Sort both; give each child the smallest cookie that satisfies them
  11. Lemonade Change (Easy): Track $5 and $10 counts; for $20 prefer giving 10+5 over 5+5+5
  12. Maximum Units on a Truck (Easy): Fractional-knapsack style: take boxes with the most units first
  13. Best Time to Buy and Sell Stock II (Medium): Sum every positive day-to-day increase
  14. Two City Scheduling (Medium): Sort by costA − costB; send the first half to A
  15. Minimum Number of Refueling Stops (Hard): Drive as far as possible; when stuck, retroactively refuel at the biggest passed station (max-heap)