Topic 12 of 14
Greedy Patterns
2 patterns and 10 practice problems, each with a recall tip, a diagram, the theory and a Python template.
01
Greedy - Interval Scheduling
5 practice problems
Theory
- Sort intervals by end time. Greedily pick the earliest-finishing non-overlapping interval.
- For "minimum rooms / resources": sort by start, use a min-heap of end times.
- For "merge intervals": sort by start, extend or create new merged interval.
- Exchange argument proves greedy is optimal here.
Code template
python
def erase_overlap_intervals(intervals):
intervals.sort(key=lambda x: x[1])
count = 0
end = float('-inf')
for s, e in intervals:
if s >= end:
end = e
else:
count += 1 # remove this interval
return count
def merge_intervals(intervals):
intervals.sort()
merged = [intervals[0]]
for s, e in intervals[1:]:
if s <= merged[-1][1]:
merged[-1][1] = max(merged[-1][1], e)
else:
merged.append([s, e])
return mergedPractice problems · 5
Medium#56
Medium#435
Medium#57
Medium#253
Medium#452
02
Greedy - Kadane's / Jump Game
5 practice problems
Theory
- Kadane's algorithm: track a running sum. Reset to 0 (or current element) when it goes negative.
- Jump game: track the farthest reachable index. If current index > farthest — can't reach.
- Jump game II: BFS levels — track the farthest you can reach from the current "level" of jumps.
- These are greedy because the locally optimal choice (take the best option now) is globally optimal.
Code template
python
def max_subarray(nums):
max_sum = curr_sum = nums[0]
for num in nums[1:]:
curr_sum = max(num, curr_sum + num)
max_sum = max(max_sum, curr_sum)
return max_sum
def can_jump(nums):
farthest = 0
for i in range(len(nums)):
if i > farthest:
return False
farthest = max(farthest, i + nums[i])
return TruePractice problems · 5
Medium#53
Medium#55
Medium#45
Medium#134
Easy#121
Spotted a mistake on this page?
Wrong formula, broken animation or confusing wording. Tell us and we will fix it.