Schedule Courses before deadlines
Picture
A course taking 3 days with deadline 5 must fit before day 5 alongside all earlier chosen courses.
Predict
Why remove the longest chosen duration when a deadline is missed?
Walk through the small example
It frees most time for the same one-course loss. Deadline order exposes violated prefixes; replacing the longest chosen job maximizes remaining room without reducing count more than necessary.
Mental model and complete Python solution
Keep a feasible-looking set through each deadline. If its total time is too large, one course must leave; evicting the longest produces the smallest possible total for that count.
What the function promises: Return the maximum course count for nonnegative durations and deadlines.
from heapq import heappush, heappop
def max_courses(courses):
total, chosen = 0, []
for duration, deadline in sorted(courses, key=lambda item: item[1]):
total += duration
heappush(chosen, -duration)
if total > deadline:
total += heappop(chosen)
return len(chosen)
assert max_courses([(100,200),(200,1300),(1000,1250),(2000,3200)]) == 3
assert max_courses([]) == 0
Work and storage: O(n log n) time and O(n) heap space.
When to recognize it: Deadline order exposes violated prefixes; replacing the longest chosen job maximizes remaining room without reducing count more than necessary.
Check before applying it: This proof maximizes count, not reward, and assumes every course is available from time zero.
Change one rule
Courses carry different rewards.
See what changes
Count-preserving replacement is no longer enough; use a reward-aware DP or another justified objective-specific method.
Connect
greedy proof: An exchange replaces a chosen course without reducing count.
Heap: keep the next extreme ready: A max-heap exposes the most expensive chosen duration.