621. Task Scheduler
https://leetcode.com/problems/task-scheduler/
Given a char array representing tasks CPU need to do. It contains capital letters A to Z where different letters represent different tasks. Tasks could be done without original order. Each task could be done in one interval. For each interval, CPU could finish one task or just be idle.
However, there is a non-negative cooling interval n that means between two same tasks, there must be at least n intervals that CPU are doing different tasks or just be idle.
You need to return the least number of intervals the CPU will take to finish all the given tasks.
Example:
Input: tasks = ["A","A","A","B","B","B"], n = 2 Output: 8 Explanation: A -> B -> idle -> A -> B -> idle -> A -> B.
Constraints:
- The number of tasks is in the range
[1, 10000]. - The integer
nis in the range[0, 100].
---
Intuition
Use most frequent task/char first
Priority Queue can keep the most frequent on top
N gaps in between. => pop N + 1 elements .. 0 through N from pq.. while !pq.isEmpty
if freq-- is > 0 => save in next list
increment ans everytime you pop
if pq is empty and next list is empty => no more elements to process => return ans
pq.addAll(next) and continue till !pq.isEmpty
---
Time - O(N log 26) => O(N)
Space - O(26) => O(1)
---
Related problems
---