Task Scheduler

Introduction

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.

1
2
3
4
Example 1:
Input: tasks = ['A','A','A','B','B','B'], n = 2
Output: 8
Explanation: A -> B -> idle -> A -> B -> idle -> A -> B.
Note: The number of tasks is in the range [1, 10000]. The integer n is in the range [0, 100].

Solution

This problem is very similar to another problem in Leetcode Rearrange string k distance apart. Keep a heap to store the occurrence of each character in descending order, pop out the task with largest occurrence to maximize the usage of empty interval, then pop out another n tasks from heap and store them in temporary array with each minus one, after the end of cooling interval, put temporary array back to heap for the next run.

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
29
30
31
32
public class TaskScheduler {
public int leastInterval(char[] tasks, int n) {
int[] map = new int[26];
for(char c : tasks) map[c - 'A']++;
PriorityQueue<Integer> queue = new PriorityQueue<>((a, b) -> b - a);
for(int f : map) {
if(f > 0) queue.add(f);
}

int times = 0;
while(!queue.isEmpty()) {
List<Integer> temp = new ArrayList<>();
for(int i=0; i<=n; i++) {
if(!queue.isEmpty()) {
if(queue.peek() > 1) {
temp.add(queue.poll()-1);
}
else {
queue.poll();
}
}
times++;
if(queue.isEmpty() && temp.size() == 0) {
break;
}
}

for(int l : temp) queue.add(l);
}
return times;
}
}