forked from neetcode-gh/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path0621-task-scheduler.kt
More file actions
28 lines (28 loc) · 906 Bytes
/
0621-task-scheduler.kt
File metadata and controls
28 lines (28 loc) · 906 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
class Solution {
fun leastInterval(tasks: CharArray, n: Int): Int {
if(n == 0)
return tasks.size
val hm = HashMap<Char,Int>()
for(task in tasks)
hm[task] = hm.getOrDefault(task, 0) + 1
val maxHeap = PriorityQueue<Int>(compareBy{-it})
for(count in hm.values)
maxHeap.add(count)
val q = ArrayDeque<Pair<Int,Int>>() // time, value
var time = 0
while(!maxHeap.isEmpty() || !q.isEmpty()){
if(!maxHeap.isEmpty()){
var current = maxHeap.poll()
current--
if(current > 0)
q.add(Pair(time+n,current))
}
if(!q.isEmpty()){
if(q.peek().first == time)
maxHeap.add(q.poll().second)
}
time++
}
return time
}
}