Skip to content

Instantly share code, notes, and snippets.

@hsaputra
Created November 8, 2018 22:33
Show Gist options
  • Save hsaputra/668ceb02684ec052231b7030b5947412 to your computer and use it in GitHub Desktop.
Save hsaputra/668ceb02684ec052231b7030b5947412 to your computer and use it in GitHub Desktop.
class Solution {
public int leastInterval(char[] tasks, int n) {
if (n < 0 ) {
return 0;
}
// Group tasks
int[] count = new int[26];
for (char cur : tasks) {
int pos = cur - 'A';
count[pos]++;
}
// Sort
Arrays.sort(count);
// Iterate through sorted array and for each larger elements go to diff tasks
// until n cool down
int time = 0;
while(count[25] > 0) {
int i = 0;
while (i <= n) {
// stopping
if (count[25] == 0) {
break;
}
if (i < 26 && count[25 - i] > 0) {
count[25 - i]--;
}
time++;
i++;
}
// Resort
Arrays.sort(count);
}
return time;
}
}
@hsaputra
Copy link
Author

hsaputra commented Nov 9, 2018

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.
 

Note:

The number of tasks is in the range [1, 10000].
The integer n is in the range [0, 100].

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment