-
Notifications
You must be signed in to change notification settings - Fork 2.3k
/
0621-task-scheduler.py
31 lines (26 loc) · 988 Bytes
/
0621-task-scheduler.py
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
29
30
31
class Solution:
def leastInterval(self, tasks: List[str], n: int) -> int:
count = Counter(tasks)
maxHeap = [-cnt for cnt in count.values()]
heapq.heapify(maxHeap)
time = 0
q = deque() # pairs of [-cnt, idleTime]
while maxHeap or q:
time += 1
if not maxHeap:
time = q[0][1]
else:
cnt = 1 + heapq.heappop(maxHeap)
if cnt:
q.append([cnt, time + n])
if q and q[0][1] == time:
heapq.heappush(maxHeap, q.popleft()[0])
return time
# Greedy algorithm
class Solution(object):
def leastInterval(self, tasks: List[str], n: int) -> int:
counter = collections.Counter(tasks)
max_count = max(counter.values())
min_time = (max_count - 1) * (n + 1) + \
sum(map(lambda count: count == max_count, counter.values()))
return max(min_time, len(tasks))