-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathtaskScheduler.java
More file actions
30 lines (22 loc) · 1.66 KB
/
taskScheduler.java
File metadata and controls
30 lines (22 loc) · 1.66 KB
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
public int leastInterval(char[] tasks, int n) {
int task[] = new int[26]; // Task array to store the count of each task,
// initialised to 0.
for(char i : tasks) // For-each loop to iterate over tasks and update the task
task[i - 'A']++; // frequencies simultaneously.
Arrays.sort(task); // Sorting the frequencies in ascending order so
// that the highest frequencies come to last.
int max_v = task[25] - 1; // Max value of frequency of tasks.
int idle = max_v * n; // Maximum number of idle slots we can have.
for(int i = 24; i >= 0; i--){ // Iterating over frequencies, except the
// maximum freq. we obtained earlier
idle = idle - Math.min(max_v, task[i]); // Updating the idle slots because as we do
// some more tasks, the slots would be
// filled and no. of idle slots will reduce.
}
if(idle < 0) // If all idle slots are filled or there are even more tasks than no.
idle = 0; // of idle slots, our answer would be no. of tasks in total i.e.
// CPU would be busy the entire time, and cooldown time between all
// tasks would be satisfied.
// Total cycles needed. If there are idle slots present
return tasks.length + idle; // we add them to total tasks.
}