30/41
Part 6 of 7 · The worked exampleLearn and do

Sorted by end time, bisect_right counts the jobs that can still run

Back to the render jobs. Sort them by end time and fill the same table in that order. Skipping job i still leaves best[i]. Taking it now adds its pay to best[j], where j counts the jobs that can run before it: the ones that end at or before its start.

The ends are sorted, so those jobs are a prefix of the list, and its length is bisect_right(ends, start). That's the latest at or before, again. In the warm-up, j was always i - 1. Here a search finds it.

jobs = [(1, 5, 70), (9, 14, 100), (0, 4, 60), (6, 11, 20), (4, 6, 40), (7, 10, 30)]
print(most_pay(jobs))
200

Every job that ends at or before start also ends before this job's own end, since start < end. So j never counts this job or a later one.

Trace it with ends = [4, 5, 6, 10, 11, 14], one row per job in end order. Skip is best[i], take is the pay plus best[j], and the larger is best[i + 1]:

Job ijSkipTakeBest
(0, 4, 60)0060 + 060
(1, 5, 70)06070 + 070
(4, 6, 40)17040 + 60100
(7, 10, 30)310030 + 100130
(6, 11, 20)313020 + 100130
(9, 14, 100)3130100 + 100200

The row for (4, 6, 40) is where the clarification pays off. bisect_right(ends, 4) is 1, so the job that ends at 4 counts as done in time. With bisect_left it would be 0, and the function returns 170.

Test it against the subsets. On 300 random lists of up to 9 jobs, most_pay matched the best subset every time.

Give the cost. The sort is O(n log n), and each job does one binary search, so it's O(n log n) time and O(n) memory. It took 0.3 ms for 1,000 jobs, 3.6 ms for 10,000 and 46.2 ms for 100,000.

In the editor, write most_pay(jobs), the function the code above calls. It prints the most pay from the six render jobs.