Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- '''
- Given a characters array tasks, representing the tasks a CPU needs to do, where each letter represents a different task. Tasks could be done in any order. Each task is done in one unit of time. For each unit of time, the CPU could complete either one task or just be idle.
- However, there is a non-negative integer n that represents the cooldown period between two same tasks (the same letter in the array), that is that there must be at least n units of time between any two same tasks.
- Return the least number of units of times that the CPU will take to finish all the given tasks.
- '''
- #Method 1:
- import heapq as hq
- class Solution:
- def leastInterval(self, tasks: List[str], n: int) -> int:
- time=0
- q=deque()
- d=Counter(tasks)
- h=[-i for i in d.values()]
- hq.heapify(h)
- time=0
- while h or q:
- if q and q[0][1]==time:#If cool down period over for a task just add them back to queue
- hq.heappush(h,q.popleft()[0])
- time+=1#increment timer
- if h:#If heap is not empty pick the max freq element
- val=hq.heappop(h)
- val=val+1#reduce frequency. Since it is maxheap python uses negative value
- if val!=0:#if frequency didnt reach zero add back to queue
- q.append((val,time+n))
- return time
- #Method 2:
- class Solution:
- def leastInterval(self, tasks: List[str], n: int) -> int:
- d=Counter(tasks)
- vals=list(d.values())
- maxfreq=max(vals)
- maxfreq_tasks=vals.count(maxfreq)
- ans=(maxfreq-1)*(1+n)+maxfreq_tasks#A - -A - -A you can uderstand how this formula generated
- #in above formula maxfreq_tasks are the tasks which have the frequency =max(freq(taskss))
- return max(ans,len(tasks))#some times above formula gives answer less than length of tasks. So to avoid u can do this
Add Comment
Please, Sign In to add comment