Given an array of CPU tasks and a cooldown interval n, find the minimum number of intervals needed to execute all tasks. Identical tasks must be separated by at least n intervals.
Task: You are given an array of CPU tasks, each represented by letters A to Z, and a cooldown time n. Each cycle or interval allows the completion of one task. Output the minimum number of intervals required to complete all tasks.
Constraints:
Example:
tasks = ["A","A","A","B","B","B"], n = 2 → Output: 8Schedule: A → B → idle → A → B → idle → A → B
fun leastInterval(tasks: CharArray, n: Int): Int { val freq = IntArray(26) for (task in tasks) { freq[task - 'A'] += 1 } val maxFreq = freq.max() val maxCount = freq.count { it == maxFreq } // Formula: (maxFreq - 1) * (n + 1) + maxCount val result = (maxFreq - 1) * (n + 1) + maxCount return maxOf(result, tasks.size)}
The greedy approach uses a mathematical formula based on the most frequent task.
If a task appears max_freq times, we need at least (max_freq - 1) × (n + 1) + max_count
intervals, where max_count is the number of tasks with maximum frequency.
The intuition: arrange the most frequent task with cooldown gaps, then fill the gaps with other tasks. If we have enough variety, no idle time is needed and the answer is simply the total number of tasks.
(max_freq - 1) × (n + 1) + max_countTime Complexity: O(n) where n is the number of tasks
Space Complexity: O(1) - fixed size array for 26 letters