Review Note

Last Update: 07/03/2024 02:06 AM

Current Deck: LeetCode

Published

Fields:

Front
621. Task Scheduler
  • You are given an array of CPU tasks, each represented by letters A to Z, and a cooling time, n. Each cycle or interval allows the completion of one task. Tasks can be completed in any order, but there's a constraint: identical tasks must be separated by at least n intervals due to cooling time.
  • ​Return the minimum number of intervals required to complete all tasks.
Back
class Solution:
    def leastInterval(self, tasks: List[str], n: int) -> int:
        counterHeap = [-count for count in Counter(tasks).values()] # Negative values for max heap
        heapq.heapify(counterHeap)
        cooldownQueue = deque()
        intervals = 0
        while counterHeap or cooldownQueue:
            intervals += 1
            if cooldownQueue and intervals == cooldownQueue[0][0]:
                heapq.heappush(counterHeap, cooldownQueue.popleft()[1])
            if counterHeap:
                count = heapq.heappop(counterHeap)
                if count < -1:
                    cooldownQueue.append((intervals + n + 1, count + 1))
        return intervals

class Solution:
    def leastInterval(self, tasks: List[str], n: int) -> int:
        count = [0] * 26
        ordA = ord('A')
        for t in tasks:
            count[ord(t) - ordA] += 1
        maxCount, maxFreq = max(count), 0
        for c in count:
            if c == maxCount:
                maxFreq += 1
        return max((maxCount - 1) * (n + 1) + maxFreq, len(tasks))


Tags:

Trees

Suggested Changes:

Deck Changes (Suggestion to move the Note to the following Deck):

Field Changes:

Tag Changes: