Payments app~25 min2s · 256 MBtarget O(n log n) time, O(n) spacegreedy
You work on a payments app. At the start of the night a single processor becomes free at minute ready_at. It runs payout jobs one after another, and each job needs a number of minutes.
Every job has a bank cut-off, a minute by which it must be finished. Your team lead asks: "What is the largest number of jobs we can finish on time?" Jobs that are not chosen are skipped. There can be 100,000 jobs.
Write max_on_time(durations, deadlines, ready_at).
durations[i] is the number of minutes job i needs, and deadlines[i] is the minute by which it must end.ready_at. It runs one job at a time, with no gaps, and a job cannot be paused.Input: durations = [4, 2, 3, 5, 1], deadlines = [6, 5, 8, 7, 3], ready_at = 0
Output: 3Take the jobs in order of deadline and add each to the chosen set. When the clock passes the deadline of the job most recently added, drop the longest chosen job.
| Next run by deadline | Clock after adding | Longest run dropped | Runs kept |
|---|---|---|---|
| run 4 (takes 1, due 3) | 1 | none | 1 |
| run 1 (takes 2, due 5) | 3 | none | 2 |
| run 0 (takes 4, due 6) | 7 | 4 | 2 |
| run 3 (takes 5, due 7) | 8 | 5 | 2 |
| run 2 (takes 3, due 8) | 6 | none | 3 |
The set that remains has 3 jobs.
Input: durations = [5], deadlines = [4], ready_at = 0
Output: 0The only job needs 5 minutes but is due at minute 4, so no job can finish on time.
Input: durations = [3, 3], deadlines = [10, 10], ready_at = 5
Output: 1The processor is free at minute 5. The first job ends at 8 and the second at 11. The second is due at 10, so only one job is on time.
1 ≤ len(durations) = len(deadlines) ≤ 100,0001 ≤ durations[i] ≤ 1,000,0001 ≤ deadlines[i] ≤ 1,000,000,0000 ≤ ready_at ≤ 1,000,000Trying every subset of the jobs means 2^100,000 subsets, and trying every order is even larger. A sort and a heap cost about 1.7 million steps. So we must decide, one job at a time, whether to keep it, and we must be able to undo a bad choice.