You are given a char array representing tasks CPU need to do. It contains capital letters A to Z where each letter represents a different task. Tasks could be done without the original order of the array. 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
nthat represents the cooldown period between two same tasks (the same letter in the array), that is that there must be at least
nunits of time between any two same tasks. You need to 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
This question is more about logic than coding. As only the number of units of times is asked, the key is to find a qualified arrangement of tasks and its time accordingly.
tasks=[A,A,A,B,B,B,C,C,D,D],n=3 as an example, we have a variable
mx: the maximum frequency of tasks. In this case,
mx=3 (3 A and 3 B). Besides, there are totally
x tasks appear
mx. We can divide the arrangement into two parts: the first one consist of
mx-1 chunks with the length equals to
n+1; the second part consist of
Then we use greedy when filling in the idle times. We put the remaining tasks sequentially to the chunks round by round, evenly filled in idle times.
In this case, it’s easy to find out that the total time is
(mx-1)*(n+1)+x. This is actually the lower bound to process these tasks: when
n gets really large, we have to hold this much time to satisfy that there are n timeslots between two same tasks.
When n is small and after taking all idle times, however, we can safely place remaining tasks into the chunks, and the chunk size expands. In this case, there’s no idle time and the answer is simply the number of tasks.
class Solution: def leastInterval(self, tasks: List[str], n: int) -> int: counter = list(collections.Counter(tasks).values()) mx = max(counter) i = counter.count(mx) return max(len(tasks),(mx-1)*(n+1)+i)