Beyond A level · 5 exercises
Python greedy algorithms
Take the best-looking choice at each step and never go back: sorting first usually makes the best choice obvious.
It works only when a local best choice can't spoil the whole answer; for meetings, choosing the one that ends earliest leaves the most room.
meetings = [(1, 4), (3, 5), (0, 6), (5, 7)]
end, count = -1, 0
for s, e in sorted(meetings, key=lambda m: m[1]):
if s >= end:
count += 1
end = e
print(count)Watch for: Sorting by the wrong thing (start instead of end) gives a plausible but wrong answer: try a small case by hand.
Exercises
- Most meetingsOne room, many meetings with start and end times.Expert
- Rooms neededGiven meetings with start and end times, how many rooms are needed so that noneExpert
- Fewest jumpsEach number says how far you may jump forward from that position.Expert
- Fractional knapsackItems can be cut, so you may take part of one.Expert
- Joining ropesJoining two ropes costs the sum of their lengths.Expert