MCPcopy Create free account
hub / github.com/neetcode-gh/leetcode / leastInterval

Method leastInterval

java/0621-task-scheduler.java:3–25  ·  view source on GitHub ↗
(char[] tasks, int n)

Source from the content-addressed store, hash-verified

1class 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}

Callers

nothing calls this directly

Calls 4

addMethod · 0.45
isEmptyMethod · 0.45
peekMethod · 0.45
getKeyMethod · 0.45

Tested by

no test coverage detected