0%

Task Scheduler

Question

Given a char array representing tasks CPU need to do. It contains capital letters A to Z where different letters represent different tasks. Tasks could be done without original order. Each task could be done in one interval. For each interval, CPU could finish one task or just be idle.

However, there is a non-negative cooling interval n that means between two same tasks, there must be at least n intervals that CPU are doing different tasks or just be idle.

You need to return the least number of intervals the CPU will take to finish all the given tasks.

Example:
Input: tasks = [“A”,”A”,”A”,”B”,”B”,”B”], n = 2
Output: 8
Explanation: A -> B -> idle -> A -> B -> idle -> A -> B.

Solution

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
/*
A math problem, what matter is numbers of letter that counts most;
AAABBB
A~~A~~AB
*/
public int leastInterval(char[] tasks, int n) {
if (tasks.length <= 1) {
return tasks.length;
}

int[] num = new int[26];
for (char t : tasks) {
num[t-'A']++;
}

Arrays.sort(num);
// calculater numbers of letter that counts most; in this case, 2;
int i = 25;
while (i >= 0 && num[i] == num[25]) {
i--;
}

// compare with tasks.length;
// num[25]-1 is interval;
// n+1 means A~~A~~, 出现次数最多的字母A,A最后一组之前的数量,
//再加上与A相同的字母的数量 25-i
return Math.max(tasks.length, (num[25]-1) * (n+1) + 25-i);
}