Engineering platform~25 min2s · 256 MBtarget O(n log n) time, O(n) spacegreedy · sorting · heaps
A platform team has a queue of maintenance jobs, and one worker runs one job at a time. Every job takes one time unit. A job has a deadline, the last time unit in which it may finish, and a reward for finishing in time. Choose which jobs to run, and when, to collect the largest total reward.
Write best_reward_by_deadlines(tasks).
tasks[i] = [deadline, reward]. A task with deadline d must run in one of the time units 1 to d.Input: tasks = [[2, 50], [1, 30], [2, 40], [3, 10], [1, 60]]
Output: 120Sort by deadline. Keep the chosen rewards in a min-heap. After adding a task, if more tasks are kept than its deadline allows, drop the smallest reward.
| Task [deadline, reward] | Kept rewards before | Too many for the deadline? | Kept rewards after |
|---|---|---|---|
| [1, 30] | [] | no | [30] |
| [1, 60] | [30] | yes: drop 30 | [60] |
| [2, 50] | [60] | no | [50, 60] |
| [2, 40] | [50, 60] | yes: drop 40 | [50, 60] |
| [3, 10] | [50, 60] | no | [10, 50, 60] |
The kept rewards are 10, 50 and 60, so the largest total is 120.
Input: tasks = [[1, 5], [1, 9]]
Output: 9Both need time unit 1, so only one can run. The larger reward wins: 9.
Input: tasks = [[5, 7], [5, 3]]
Output: 10Both fit before time unit 5, so the total is 10.
0 ≤ tasks.length ≤ 100,000 (jobs)1 ≤ deadline ≤ 1,000,000,000 (time units)0 ≤ reward ≤ 1,000,000,000Trying every subset of jobs costs 2 to the power n, which is far beyond reach. A sort costs n log n, and each heap step costs log n, so the whole job fits easily.