The problem involves scheduling tasks on the minimum number of machines such that no two tasks overlap on the same machine. Each task has a start time and an end time.
To solve this efficiently, we use a min-heap to track the end times of tasks currently assigned to machines:
class Solution {
public int minMachines(int[][] tasks) {
// Step 1: Sort tasks by start time
Arrays.sort(tasks, (a, b) -> a[0] - b[0]);
// Step 2: Use a min-heap to track end times of tasks
PriorityQueue<Integer> minHeap = new PriorityQueue<>();
for (int[] task : tasks) {
int start = task[0];
int end = task[1];
// Step 3: If the current task can reuse a machine, remove the earliest end time
if (!minHeap.isEmpty() && minHeap.peek() <= start) {
minHeap.poll();
}
// Step 4: Add the current task's end time to the heap
minHeap.offer(end);
}
// Step 5: The size of the heap is the minimum number of machines required
return minHeap.size();
}
}
O(n log n)
โ Sorting the tasks by start time.O(n log n)
โ Adding and removing elements from the heap for n
tasks.O(n log n)
.Input: tasks = [[0, 30], [5, 10], [15, 20]]
Output: 2
Explanation:
- Task 1: [0, 30] requires a machine.
- Task 2: [5, 10] requires a second machine.
- Task 3: [15, 20] can reuse the second machine after Task 2 ends.