Heap simulation
Time O(T log 26) Space O(26)Each round of n + 1 slots, pop up to n + 1 different tasks with the most copies left, run them, and push back those that still have copies. A full round costs n + 1 units unless it's the last.
import java.util.*;
class Solution {
public int leastInterval(char[] tasks, int n) {
int[] count = new int[26];
for (char t : tasks) count[t - 'A']++;
PriorityQueue<Integer> pq = new PriorityQueue<>(Comparator.reverseOrder());
for (int c : count) if (c > 0) pq.offer(c);
int time = 0;
while (!pq.isEmpty()) {
List<Integer> left = new ArrayList<>();
int ran = 0;
for (int slot = 0; slot <= n && !pq.isEmpty(); slot++) {
int c = pq.poll();
if (c > 1) left.add(c - 1);
ran++;
}
for (int c : left) pq.offer(c);
time += pq.isEmpty() ? ran : n + 1;
}
return time;
}
}Verdict: Shows why the greedy is right.