โ† Back to Heap Pattern

๐Ÿ“š Schedule Tasks on Minimum Machines โ€“ Java Cheat Sheet

๐Ÿ“Œ What Is It?

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:

๐Ÿงฑ Pattern Template

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();
    }
}

๐Ÿ“Š Time Complexity

โœ… Use Cases

๐Ÿ“˜ Common LeetCode Problems

๐Ÿงช Example: Schedule Tasks on Minimum Machines

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.

๐Ÿ’ก Pro Tips