물음표 살인마의 개발블로그

알고리즘 문제/Leetcode

621. Task Scheduler

BEstyle 2023. 1. 31. 13:19

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.

 

Example 1:

Input: tasks = ["A","A","A","B","B","B"], n = 2
Output: 8
Explanation: 
A -> B -> idle -> A -> B -> idle -> A -> B
There is at least 2 units of time between any two same tasks.

Example 2:

Input: tasks = ["A","A","A","B","B","B"], n = 0
Output: 6
Explanation: On this case any permutation of size 6 would work since n = 0.
["A","A","A","B","B","B"]
["A","B","A","B","A","B"]
["B","B","B","A","A","A"]
...
And so on.

Example 3:

Input: tasks = ["A","A","A","A","A","A","B","C","D","E","F","G"], n = 2
Output: 16
Explanation: 
One possible solution is
A -> B -> C -> A -> D -> E -> A -> F -> G -> A -> idle -> idle -> A -> idle -> idle -> A

 

Constraints:

  • 1 <= task.length <= 104
  • tasks[i] is upper-case English letter.
  • The integer n is in the range [0, 100].

# https://leetcode.com/problems/task-scheduler/description/

'''
1. 아이디어 :
    1)  Heap을 이용하여 가장 많이 사용되는 알파벳의 개수를 Counter로 구한다.
        스택 배열과 time 변수를 만들어서, while문을 돌려가면서 가장 많이 사용된 알파벳을 스택에 넣는다.
        스택에 넣을 때마다 time을 1씩 증가시키고, 스택의 길이가 n보다 작을 때까지 스택에 넣는다.
        스택의 길이가 n이 되면, 스택의 길이만큼 time을 증가시키고, 스택을 비운다.
        스택을 비울 때마다, 가장 많이 사용된 알파벳의 개수를 1씩 감소시킨다.
        가장 많이 사용된 알파벳의 개수가 0이 되면, 다음으로 많이 사용된 알파벳을 스택에 넣는다.
        힙과 스택에 값이 없으면, time을 리턴한다.
2. 시간복잡도 :
    1) O(n) + O(time) = O(n)
    - n개의 원소를 넣고 빼는 작업 + time만큼의 while 작업
3. 자료구조 :
    1) Heap, Stack
'''


from collections import Counter
class Solution:
    def leastInterval(self, tasks: List[str], n: int) -> int:
        c = Counter(tasks)
        tasks = []
        stack = deque()
        for key,val in c.items():
            tasks.append(-val)
        heapq.heapify(tasks)
        print(tasks)

        t=0
        while tasks or stack:
            if tasks:
                num = -heapq.heappop(tasks)
                num -= 1
                if num !=0:
                    stack.append([num,t+n])

            while stack and stack[0][1]==t:
                num = -stack.popleft()[0]
                heapq.heappush(tasks,num)
            t+=1
        return t

'알고리즘 문제 > Leetcode' 카테고리의 다른 글

57. Insert Interval  (0) 2023.02.01
252. Meeting Rooms  (0) 2023.02.01
965. Univalued Binary Tree  (0) 2023.01.27
222. Count Complete Tree Nodes  (0) 2023.01.27
257. Binary Tree Paths  (0) 2023.01.27