| 1 | class Solution { |
| 2 | |
| 3 | public int leastInterval(char[] tasks, int n) { |
| 4 | if (n == 0) return tasks.length; |
| 5 | PriorityQueue<Integer> pq = new PriorityQueue<>((a, b) -> b - a); |
| 6 | Queue<Pair<Integer, Integer>> q = new LinkedList<>(); |
| 7 | int[] arr = new int[26]; |
| 8 | for (char c : tasks) arr[c - 'A']++; |
| 9 | for (int val : arr) if (val > 0) pq.add(val); |
| 10 | int time = 0; |
| 11 | |
| 12 | while ((!pq.isEmpty() || !q.isEmpty())) { |
| 13 | time++; |
| 14 | if (!pq.isEmpty()) { |
| 15 | int val = pq.poll(); |
| 16 | val--; |
| 17 | if (val > 0) q.add(new Pair(val, time + n)); |
| 18 | } |
| 19 | |
| 20 | if (!q.isEmpty() && q.peek().getValue() == time) pq.add( |
| 21 | q.poll().getKey() |
| 22 | ); |
| 23 | } |
| 24 | return time; |
| 25 | } |
| 26 | } |