Sub topic 2
Proving Correctness: The Exchange Argument
This chapter assumes you can read Python, know Big-O notation, and are comfortable with proof by contradiction.
The Exchange Argument
An exchange argument starts from any optimal solution, called OPT, that differs from the greedy solution. You then swap one of OPT's choices for the greedy choice and show the result is no worse. After enough swaps, OPT has become the greedy solution without losing quality, so the greedy solution is optimal too.
Activity Selection: Earliest Finish Time First
Sort the intervals by finish time and take each one that starts after the last chosen one ends. For the exchange argument, swap OPT's first interval for the one that finishes earliest. That swap creates no overlap, so the count stays the same.
def select_activities(intervals):
chosen, last_end = [], float("-inf")
for start, end in sorted(intervals, key=lambda iv: iv[1]):
if start >= last_end:
chosen.append((start, end))
last_end = end
return chosen
print(select_activities([(1, 4), (3, 5), (0, 6), (5, 7), (8, 11)]))
# [(1, 4), (5, 7), (8, 11)]A common error is sorting by start time or by shortest length. Both choices fail on simple inputs.
Interval Partitioning: Fewest Rooms
To find the fewest rooms, process the intervals by start time. Reuse the room that frees up earliest, and track the end times in a min-heap. The answer equals the depth, which is the largest number of intervals that overlap at any single point. No schedule can use fewer rooms than the depth.
Fractional Knapsack: Best Value per Weight
In the fractional knapsack you may take part of an item. Take items in decreasing order of value per weight. If OPT holds weight from a lower-ratio item while a higher-ratio item is left out, swapping equal weight between them raises the total value or leaves it unchanged.
def fractional_knapsack(items, capacity):
total = 0.0
for value, weight in sorted(items, key=lambda it: it[0] / it[1], reverse=True):
take = min(weight, capacity)
total += value * take / weight
capacity -= take
return total
print(fractional_knapsack([(60, 10), (100, 20), (120, 30)], 50)) # 240.0Minimizing Lateness: Earliest Deadline First
A job's lateness is how far past its deadline it finishes. To minimize the maximum lateness, schedule the jobs in order of deadline. An inversion is a pair of jobs where the one with the later deadline runs first. If OPT has an inversion, some adjacent pair is inverted, and swapping that pair never increases the maximum lateness.
def max_lateness(jobs): # (duration, deadline)
t, worst = 0, 0
for duration, deadline in sorted(jobs, key=lambda j: j[1]):
t += duration
worst = max(worst, t - deadline)
return worst
print(max_lateness([(3, 6), (2, 8), (1, 9), (4, 9), (3, 14), (2, 15)])) # 1Exercise
In the lateness proof, why is it enough to swap adjacent inverted jobs?
Show answer
Any schedule with an inversion has an adjacent inverted pair. Swapping that pair removes one inversion, and the maximum lateness does not go up. Repeating the swap reaches the earliest-deadline order without making the schedule worse.
Exercise
Give items and a capacity where greedy by value per weight fails for 0/1 knapsack.
Show answer
Use the items (value 60, weight 10), (100, 20), (120, 30) with capacity 50. Greedy takes the first two items for a value of 160. Taking the second and third items gives 220.