LeetCode 2365: Task Scheduler II
Problem Description
Explanation
To solve this problem, we can simulate the task completion process day by day. We keep track of the last day each task type was completed and use that information to decide whether we can perform the task on the current day or if a break is needed. We maintain a priority queue to store the tasks based on the next available day they can be completed.
- Create a map to store the last completion day of each task type.
- Create a priority queue to store tasks based on the next available day they can be completed.
- Iterate over the tasks and update the last completion day in the map.
- For each task, check if it can be completed on the current day based on the space constraint. If not, add it to the priority queue.
- If the priority queue is not empty, simulate taking a break until the next task can be performed and update the current day accordingly.
- Repeat the process until all tasks are completed.
Time Complexity: O(n log n) where n is the number of tasks Space Complexity: O(n)
Solutions
class Solution {
public int taskScheduler(int[] tasks, int space) {
Map<Integer, Integer> lastCompletion = new HashMap<>();
PriorityQueue<int[]> pq = new PriorityQueue<>((a, b) -> a[1] - b[1]);
int day = 0;
for (int i = 0; i < tasks.length; i++) {
int task = tasks[i];
if (lastCompletion.containsKey(task) && day - lastCompletion.get(task) <= space) {
pq.offer(new int[]{task, lastCompletion.get(task) + space + 1});
} else {
lastCompletion.put(task, day);
}
day++;
}
while (!pq.isEmpty()) {
int[] nextTask = pq.poll();
day = Math.max(day, nextTask[1]);
lastCompletion.put(nextTask[0], day);
day++;
}
return day;
}
}
Loading editor...