Task Scheduler
Given a characters array `tasks`, representing the tasks a CPU needs to do, where each letter represents a different task. Tasks could be done in any order. Each task is done in one unit of time. For each unit of time, the CPU could complete either one task or just be idle. However, there is a non-negative integer `n` that represents the cooldown period between two same tasks (the same letter in the array). Return the least number of units of times that the CPU will take to finish all the given tasks.
Examples
Constraints
1 <= task.length <= 10^4tasks[i] is upper-case English letter.The integer n is in the range [0, 100].
Approach
First, count the frequencies of each task. To minimize idle time, we should always process the task with the highest remaining frequency first. Add the frequencies to a Max Heap. Use a Queue to keep track of tasks that are currently cooling down, storing pairs of `[remaining_frequency, time_available_again]`. At each time step, if the Max Heap has tasks, pop the max, decrement its frequency, and if it's still > 0, add it to the cooling queue. Check if any task in the cooling queue is ready to be processed again and push it back to the Max Heap.
Complexity Analysis
T is the total number of tasks. The heap and queue sizes are bounded by 26 (the number of English letters), so space is O(1) and heap operations take O(1) time.
class Solution { public int leastInterval(char[] tasks, int n) { int[] counts = new int[26]; for (char c : tasks) { counts[c - 'A']++; } PriorityQueue<Integer> maxHeap = new PriorityQueue<>(Collections.reverseOrder()); for (int count : counts) { if (count > 0) maxHeap.offer(count); } Queue<int[]> q = new LinkedList<>(); // [count, availableTime] int time = 0; while (!maxHeap.isEmpty() || !q.isEmpty()) { time++; if (!maxHeap.isEmpty()) { int count = maxHeap.poll() - 1; if (count > 0) { q.offer(new int[]{count, time + n}); } } if (!q.isEmpty() && q.peek()[1] == time) { maxHeap.offer(q.poll()[0]); } } return time; }}