Practice problem · easy
You work on a streaming service. A queue of new episodes waits for one encoder. Each encoding job takes some seconds, and each episode has a due time: the second, counted from when the encoder starts, at which it should be ready.
The encoder starts at second 0. It runs one job at a time, and it starts the next job as soon as one finishes. You choose the order.
An episode that finishes encoding after its due time is late by the difference. An episode that finishes on time or early has a delay of 0.
Your team lead asks: "In the best order, how late is the latest episode?"
Write smallest_worst_delay(jobs).
jobs[i] = [seconds, due]: job i takes seconds seconds to encode, and its episode is due at second due.f, its delay is f - due when f is after due, and 0 otherwise.Input: jobs = [[4, 9], [2, 15], [3, 6], [1, 9], [3, 14], [2, 8]]
Output: 1Sort the jobs by due time, the earliest first: [3, 6], [2, 8], [4, 9], [1, 9], [3, 14], [2, 15]. Run them in that order and keep a clock.
| Job (seconds, due) | Clock after it | Delay | Worst so far |
|---|---|---|---|
| (3, 6) | 3 | 0 | 0 |
| (2, 8) | 5 | 0 | 0 |
| (4, 9) | 9 | 0 | 0 |
| (1, 9) | 10 | 1 | 1 |
| (3, 14) | 13 | 0 | 1 |
| (2, 15) | 15 | 0 | 1 |
No order does better. The four jobs due by second 9 need 3 + 2 + 4 + 1 = 10 seconds together, so one of them finishes at second 10 or later. The answer is 1.
Running the shortest job first gives a worst delay of 6 here, and running the jobs in the order given gives 7.
Input: jobs = [[1, 100], [10, 10]]
Output: 0Run the 10-second job first. It finishes at second 10, exactly when it is due. The 1-second job finishes at second 11, long before second 100.
Input: jobs = [[5, 2]]
Output: 3The only job finishes at second 5, and it was due at second 2, so it is 3 seconds late whatever you do.
0 ≤ len(jobs) ≤ 100,000, and every row is [seconds, due] with 1 ≤ seconds, due ≤ 1,000,000There can be 100,000 jobs. Trying every order is out of the question: 10 jobs already have 3,628,800 orders, and 15 jobs have more than a trillion. Sorting the jobs costs about 1.7 million steps, and one pass over them costs 100,000 more.
smallest_worst_delay · runs in your browserCoding is easiest on a laptop. On a phone, read, trace and try small edits.