
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.
1import java.util.*;
2
3class Solution {
4 public int leastInterval(char[] tasks, int n) {
5
This Java solution employs an integer array to compute task frequencies, sorts it, and calculates the idle slots required. If there are idle slots, they are added to the length of tasks; otherwise, the length of tasks is returned.
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).
1#include <vector>
#include <unordered_map>
#include <algorithm>
using namespace std;
int leastInterval(vector<char>& tasks, int n) {
unordered_map<char, int> task_map;
for (char task : tasks) task_map[task]++;
priority_queue<int> pq;
for (auto& entry : task_map) pq.push(entry.second);
int time = 0;
while (!pq.empty()) {
vector<int> tmp;
for (int i = 0; i <= n; ++i) {
if (!pq.empty()) {
tmp.push_back(pq.top() - 1);
pq.pop();
}
time++;
if (pq.empty() && tmp.empty()) break;
}
for (int count : tmp) if (count > 0) pq.push(count);
}
return time;
}
int main() {
vector<char> tasks = {'A', 'A', 'A', 'B', 'B', 'B'};
int n = 2;
return leastInterval(tasks, n); // Output: 8
}This C++ solution uses a max-heap (priority queue) to manage tasks based on their remaining frequency and efficiently handles their cooldown periods.