1def least_interval(tasks, n):
2 counts = {}
3 for t in tasks: counts[t] = counts.get(t, 0) + 1
4 max_heap = [-v for v in counts.values()]
5 max_heap.sort()
6 q = [] # (cnt, idle_until)
7 time = 0
8 while max_heap or q:
9 time += 1
10 if max_heap:
11 cnt = max_heap.pop(0)
12 if cnt + 1 < 0: q.append((cnt + 1, time + n))
13 if q and q[0][1] == time:
14 max_heap.append(q.pop(0)[0])
15 max_heap.sort()
16 return time