
Sponsored
Sponsored
The key idea is to figure out the task with the maximum frequency and set its intervals accordingly.
Assume the task with the highest frequency appears max_count times. Arrange tasks such that the remaining tasks are fitted in between the most frequent task considering the cooldown period.
The formula for the minimum intervals required is determined by the max frequency task with necessary slots due to the cooling period. The result is the maximum of the total tasks or the formed slots, i.e., max(len(tasks), (max_count - 1) * (n + 1) + count_max), where count_max is the number of tasks with frequency equal to max_count.
Time Complexity: O(N), where N is the number of tasks. Space Complexity: O(1), as the space for the frequency array is constant.
1var leastInterval = function(tasks, n) {
2 let count = new Array(26).fill(0);
3 for (let task of tasks) {
4 count[task.charCodeAt() - 'A'.charCodeAt()]++;
5 }
6 count.sort((a, b) => a - b);
7 let maxVal = count[25] - 1;
8 let idleSlots = maxVal * n;
9 for (let i = 24; i >= 0 && count[i] > 0; i--) {
10 idleSlots -= Math.min(count[i], maxVal);
11 }
12 return idleSlots > 0 ? idleSlots + tasks.length : tasks.length;
13};
14
15console.log(leastInterval(['A','A','A','B','B','B'], 2)); // Output: 8This JavaScript solution calculates task frequencies in an array, sorts them, and calculates idle slots around the frequent task arrangement, finally returning the maximum between idle slots added to task size or the task size itself.
Another way is to simulate the task processing using a priority queue to always pick the task with the highest remaining count that can be scheduled. A min-heap or a max-heap is useful to efficiently get the next task. As tasks are being processed, they are placed on cooldown before they can be executed again, managed by a cooldown queue.
Time Complexity: O(N log N), where N is determined by sorting. Space Complexity: O(1).
1using System.Collections.Generic;
using System.Linq;
class Solution {
public int LeastInterval(char[] tasks, int n) {
Dictionary<char, int> dict = new Dictionary<char, int>();
foreach (char task in tasks) {
if (dict.ContainsKey(task))
dict[task]++;
else
dict[task] = 1;
}
PriorityQueue<int, int> pq = new PriorityQueue<int, int>(Comparer<int>.Create((a, b) => b - a));
foreach (var kvp in dict) {
pq.Enqueue(kvp.Value, kvp.Value);
}
int time = 0;
while (pq.Count > 0) {
List<int> temp = new List<int>();
for (int i = 0; i <= n; ++i) {
if (pq.Count > 0) temp.Add(pq.Dequeue());
time++;
if (pq.Count == 0 && temp.Count == 0) break;
}
foreach (int count in temp) {
if (--count > 0) pq.Enqueue(count, count);
}
}
return time;
}
static void Main() {
char[] tasks = {'A', 'A', 'A', 'B', 'B', 'B'};
int n = 2;
Solution sol = new Solution();
Console.WriteLine(sol.LeastInterval(tasks, n)); // Output: 8
}
}This C# solution executes the scheduling by utilizing a priority queue to efficiently manage the tasks based on their cooldown effects.