
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.
1#include <vector>
2#include <algorithm>
3#include <cmath>
4using namespace std;
5
6int leastInterval(vector<char>& tasks, int n) {
7 vector<int> count(26, 0);
8 for (char task : tasks) {
9 count[task - 'A']++;
10 }
11 sort(count.begin(), count.end());
12
13 int max_count = count[25] - 1, idle_slots = max_count * n;
14 for (int i = 24; i >= 0 && count[i] > 0; i--) {
idle_slots -= min(count[i], max_count);
}
return idle_slots > 0 ? idle_slots + tasks.size() : tasks.size();
}
int main() {
vector<char> tasks = {'A','A','A','B','B','B'};
int n = 2;
return leastInterval(tasks, n); // Output: 8
}This C++ solution calculates the number of idle slots required in the intervals by arranging the most frequent tasks. It then fills the idle slots with remaining tasks and returns the sum of the slots and the size of tasks.
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
This JavaScript solution uses a max heap to manage tasks efficiently during the cooldown periods, thus simulating task assignment based on priority.