Iam_Sandeep

621. Task Scheduler

Jul 19th, 2022 (edited)
487
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.91 KB | None | 0 0
  1. '''
  2. 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.
  3.  
  4. 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.
  5.  
  6. Return the least number of units of times that the CPU will take to finish all the given tasks.
  7.  
  8. '''
  9. #Method 1:
  10. import heapq as hq
  11. class Solution:
  12.     def leastInterval(self, tasks: List[str], n: int) -> int:
  13.         time=0
  14.         q=deque()
  15.         d=Counter(tasks)
  16.         h=[-i for i in d.values()]
  17.         hq.heapify(h)
  18.         time=0
  19.         while h or q:
  20.             if q and q[0][1]==time:#If cool down period over for  a task just add them back to queue
  21.                 hq.heappush(h,q.popleft()[0])
  22.             time+=1#increment timer
  23.             if h:#If heap is not empty pick the max freq element
  24.                 val=hq.heappop(h)
  25.                 val=val+1#reduce frequency. Since it is maxheap python uses negative value
  26.                 if val!=0:#if frequency didnt reach zero add back to queue
  27.                     q.append((val,time+n))
  28.                
  29.  
  30.         return time
  31. #Method 2:
  32. class Solution:
  33.     def leastInterval(self, tasks: List[str], n: int) -> int:
  34.         d=Counter(tasks)
  35.         vals=list(d.values())
  36.         maxfreq=max(vals)
  37.         maxfreq_tasks=vals.count(maxfreq)
  38.         ans=(maxfreq-1)*(1+n)+maxfreq_tasks#A - -A - -A you can uderstand how this formula generated
  39.         #in above formula maxfreq_tasks are the tasks which have the frequency =max(freq(taskss))
  40.         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