Because the tasks have cooldown period, so we want the task with maximum occurrences do first.
The other task can just fill the gap between the max occurrence task.
Like task A appears most, the task order should be look like this:
A _ _ _ _ A _ _ _ _ A _ _ _ _ A …
Or A and B both have the most occurrences, task order look like this:
A B _ _ _ A B _ _ _ A B _ _ _ A B …
So the rest just fill the gap between the maxs. The minimum period between the As or ABs(gapPeriod) is the cooldown period(n) - the number of tasks that appears most(maxCount).
If the rest tasks are smaller than the total gapPeriod, which is the number of gap times the gapPeriod * max occurrence
Then we check if there is idle period, if the idle period = total gap period - number of rest tasks
if the idle period is negative, which means there is no idle period and we should put more tasks between As or ABs and set idle period to zero.
Finally, the number of period is the number of total task + number of idle period.
1 | class Solution { |