Leetcode 621 Task Scheduler

Given a characters array tasks, representing the tasks a CPU needs to do, where each letter represents a different task. Tasks could be done in any order. Each task is done in one unit of time. For each unit of time, the CPU could complete either one task or just be idle.

However, there is a non-negative integer n that represents the cooldown period between two same tasks (the same letter in the array), that is that there must be at least n units of time between any two same tasks.

Return the least number of units of times that the CPU will take to finish all the given tasks.

Input: tasks = ["A","A","A","B","B","B"], n = 2
Output: 8
Explanation: 
A -> B -> idle -> A -> B -> idle -> A -> B
There is at least 2 units of time between any two same tasks.
Input: tasks = ["A","A","A","B","B","B"], n = 0
Output: 6
Explanation: On this case any permutation of size 6 would work since n = 0.
["A","A","A","B","B","B"]
["A","B","A","B","A","B"]
["B","B","B","A","A","A"]
...
And so on.
  • The total unit time is length of list + idld time. Count the frequence of each letter. Select the most frequent letter as boundary.The the number of room that between two boundaries is boundary - 1 and the idle time unit will be at least room * n. Split other letters into rooms and each room has no same letters. If all the idle time unit all use out, we are free to expand each room so we do not need more idle time unit. This will give the result as the lenght of the given list. Otherwise if the after fill all tasks into idle time unit and there are still idle time unit not been used then we add length of given list and the available idle time units to get the result.
def leastInterval(self, tasks: List[str], n: int) -> int:
        count=[value for value in Counter(tasks).values()]
        count.sort()
        max_freq=count.pop()
        room=max_freq-1
        idle=(room)*n
        while count and idle > 0:
            idle -= min(room, count.pop())
        return max(0,idle)+len(tasks)