Greedy in practice
Implement interval scheduling maximisation and the jump game — two clean greedy algorithms that demonstrate the pattern.
- Implement interval scheduling maximisation by sorting on end time
- Implement the jump game by tracking max reach greedily
Two problems where the greedy insight is clear once named. Both are O(n) or O(n log n) and far simpler than their DP alternatives.
Two greedy implementations
Why these are greedy
Interval scheduling. Sorting by end time and always taking the earliest available interval is optimal — proved by the exchange argument: any solution that skips the earliest-finishing interval can replace its first selected interval with the earlier-finishing one without reducing the count.
Jump game. Tracking max_reach is the right "local" choice because it
captures everything reachable without committing to any specific path. At each
position i, you extend max_reach by as much as nums[i] allows. If i
exceeds max_reach, no sequence of jumps could have reached position i —
return False immediately.
Interval scheduling counts the number of intervals; a related problem asks
for the minimum number of intervals to remove so that none overlap. The
answer is total - max_non_overlapping. This duality comes up often.
Where to go next
Next: divide and conquer — splitting problems into independent sub-problems, solving each recursively, and combining results. Merge sort, binary search, and quickselect are all divide-and-conquer algorithms.
Greedy algorithms
Define greedy (locally optimal choice, never backtrack), see when greedy is provably optimal, and understand where it fails.
Divide and conquer
Split problems into independent sub-problems, recurse, combine — understand the pattern in merge sort, binary search, and quickselect, with an intuition for the Master Theorem.