Prove a local choice leads to a global optimum; classic interval scheduling, exchange arguments, and Huffman coding
Identify an invariant or exchange argument that justifies always picking the best local option.
Use when feasible solutions exist and a simple rule repeatedly improves or completes the solution.
Sort by end time and pick non-overlapping
def interval_scheduling(intervals):
intervals.sort(key=lambda x: x[1])
res=[]; end=-10**18
for s,e in intervals:
if s>=end: res.append([s,e]); end=e
return res
Swap to show optimality
# Exchange arguments are proof techniques; example: minimize sum of weighted completion times by sorting by ratio
def schedule_by_ratio(jobs):
# jobs: (weight, length)
jobs.sort(key=lambda x: x[0]/x[1], reverse=True)
return jobs
Greedy merging by frequency
import heapq
def huffman_cost(freqs):
heap=list(freqs); heapq.heapify(heap); cost=0
while len(heap)>1:
a=heapq.heappop(heap); b=heapq.heappop(heap); cost+=a+b; heapq.heappush(heap, a+b)
return cost
def template(*args, **kwargs):
# General template placeholder
pass
Sorting + linear selection.
Depends on data structures.