-
Notifications
You must be signed in to change notification settings - Fork 0
/
621. Task Scheduler
85 lines (71 loc) · 3.05 KB
/
621. Task Scheduler
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
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
/*
https://leetcode.com/problems/task-scheduler/description/
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 1:
Input: tasks = ["A","A","A","B","B","B"], n = 2
Output: 8
Explanation: A -> B -> idle -> A -> B -> idle -> A -> B.
*/
public class Solution {
private static final Logger logger = LogManager.getLogger(Solution.class);
private static final int ALPHABET_SIZE = 26;
private static final int ALPHABET_START_IDX = 65;
public int leastInterval(char[] tasks, int n) {
int[] sortedTasks = new int[ALPHABET_SIZE];
int unrealizedTasksCount = tasks.length;
if (n == 0) {
return unrealizedTasksCount;
}
for (int i = 0; i < tasks.length; i++) {
sortedTasks[tasks[i] - ALPHABET_START_IDX]++;
}
Arrays.sort(sortedTasks);
int differentTasksCount = 0;
int k = ALPHABET_SIZE - 1;
int maxTask = sortedTasks[k];
while (sortedTasks[k] >= maxTask && k > 0) {
differentTasksCount++;
k--;
}
int time = 0;
int frameSize = n >= differentTasksCount ? n : differentTasksCount;
int idleTime = n >= differentTasksCount ? 1 : 0;
int frameEmptyPlaces = frameSize;
int fullFramesCount = 0;
int currFrame = 0;
for (int i = ALPHABET_SIZE - 1; i > 0; i--) {
if (frameEmptyPlaces == 0) {
frameEmptyPlaces = frameSize;
}
if (frameEmptyPlaces == frameSize) {
while (sortedTasks[i] > 0) {
sortedTasks[i]--;
if (sortedTasks[i] > 0) {
time += frameSize + idleTime;
fullFramesCount++;
} else {
time += 1;
}
}
frameEmptyPlaces--;
} else if (frameEmptyPlaces > 0) {
while (sortedTasks[i] > 0) {
sortedTasks[i]--;
currFrame++;
if (currFrame <= fullFramesCount) {
} else if (currFrame > fullFramesCount) {
currFrame = 0;
time += 1;
frameEmptyPlaces--;
if (frameEmptyPlaces == 0) {
fullFramesCount = 0;
}
}
}
}
}
return time;
}
}