Engineering platform~25 min2s · 256 MBtarget O(n log k) time, O(k) spaceclassic twin: lc-621heaps
A build worker runs one job in each time unit, or stays idle. Each job has a kind, written as a capital letter, such as one test suite for each service. After a job of one kind runs, the same kind must rest: the next job of that kind starts after at least cooldown other time units.
Your team lead asks: "In what order should the worker run the jobs, and when does the last one finish?" Jobs can run in any order.
Write finish_time(jobs, cooldown).
jobs is a string of capital letters. Each letter is one job, and the letter is its kind.cooldown time units between them.Input: jobs = "AAABBB", cooldown = 2
Output: 8Run the kind with the most jobs left that is not resting. The table lists the kinds that can run in each unit, with their jobs left.
| Time unit | Kinds that can run (jobs left) | The worker runs |
|---|---|---|
| 1 | A (3), B (3) | A |
| 2 | B (3) | B |
| 3 | none | idle |
| 4 | A (2) | A |
| 5 | B (2) | B |
| 6 | none | idle |
| 7 | A (1) | A |
| 8 | B (1) | B |
Input: jobs = "ABC", cooldown = 5
Output: 3All three kinds are different, so none of them has to rest.
Input: jobs = "AAAA", cooldown = 3
Output: 13One kind runs 4 times with 3 time units between runs: 3 × 4 + 1 = 13.
1 ≤ length of jobs ≤ 100,000, and every letter is A to Z.0 ≤ cooldown ≤ 100,000One kind of 50,000 jobs and another of 50,000 jobs, with a cooldown of 100,000, need 4,999,950,001 time units. Stepping through them one by one, and checking all 26 kinds in each, is about 130 billion checks.
The schedule has only 100,000 jobs, and the idle units come in long runs. A method that makes one decision for each job and skips the idle runs does about 100,000 steps of a few heap operations.