Engineering platform~30 min2s · 256 MBtarget O(n) time, O(1) spaceclassic twin: lc-621greedy
A build runner executes one job in every time unit. Each job has a kind, written as a capital letter, such as one test suite for each service. Two jobs of the same kind need a cooldown between them, so that caches can settle.
An idle unit wastes the runner. The team wants the longest cooldown for which all jobs can run back to back, with no idle unit at all. The jobs may run in any order.
Write largest_idle_free_cooldown(jobs).
jobs is a string of capital letters. Each letter is one job, and the letter is its kind.c means that at least c time units pass between two jobs of the same kind. A cooldown of 0 allows equal jobs to run one after another.c for which the jobs can all run with no idle unit, in some order. If no kind occurs twice, every cooldown works, so return the number of jobs.Input: jobs = "AABBBC"
Output: 1The solution counts the jobs of each kind. The most common kind decides how much spacing the schedule can hold.
| Kind | Jobs |
|---|---|
| A | 2 |
| B | 3 |
| C | 1 |
The most common count m is 3, and one kind has it, so k is 1. There are n = 6 jobs.
The three B jobs leave m - 1 = 2 gaps. The other n - k = 5 jobs fill those gaps, so each row holds 5 / 2 = 2 units, which means a cooldown of 2 - 1 = 1. The order B A B A B C has one unit between equal jobs.
Input: jobs = "ABCDEF"
Output: 6No kind occurs twice, so a cooldown never applies. The answer is the number of jobs, 6.
Input: jobs = "AAAABB"
Output: 0Four A jobs need at least three gaps, and there are only two other jobs, so even one unit between equal jobs leaves an idle unit. Only a cooldown of 0 works.
1 ≤ len(jobs) ≤ 100,000jobs is a capital letter from A to ZTrying every order of 100,000 jobs is beyond any computer, even for one cooldown, and many cooldowns would have to be tried. Counting the jobs of each kind takes 100,000 steps, and the formula then gives the answer in one step.