Prove a local choice leads to a global optimum; classic interval scheduling, exchange arguments, and Huffman coding
# Greedy Template (Interval Scheduling)
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 resSort 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 resSwap 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 jobsGreedy 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