
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.
1from collections import Counter
2
3def leastInterval(tasks, n):
4 task_counts = list(Counter(tasks).values())
5 max_count =
This Python solution uses the collections module to count task frequencies. It calculates the minimum number of CPU intervals using the max frequency and the formula described. The result is the maximum between the total task count and the needed slots according to the maximum frequency task arrangement.
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 Python solution utilizes a priority queue (max-heap) to effectively handle the task scheduling with the intended cooldowns.