Hint: Use (b.profit - a.profit) for descending sort [OK]
Common Mistakes:
Using a.profit - b.profit for descending order
Sorting by deadline instead of profit
Using default sort without comparator
3. Given the following jobs with (id, deadline, profit): Job[] jobs = { new Job('a', 2, 100), new Job('b', 1, 19), new Job('c', 2, 27), new Job('d', 1, 25), new Job('e', 3, 15) }; What is the maximum profit achievable by scheduling these jobs before their deadlines?
Schedule 'a' at slot 2, 'c' at slot 1 (slot 2 taken), 'e' at slot 3. Total profit = 100 + 27 + 15 = 142.
Final Answer:
142 -> Option A
Quick Check:
Profit sum = 142 [OK]
Hint: Schedule highest profit jobs first in latest free slot [OK]
Common Mistakes:
Scheduling jobs without sorting by profit
Overlapping jobs in same slot
Ignoring deadlines
4. Identify the error in the following Java code snippet for job scheduling:
Arrays.sort(jobs, (a, b) -> a.profit - b.profit);
boolean[] slot = new boolean[maxDeadline + 1];
for (Job job : jobs) {
for (int j = job.deadline; j > 0; j--) {
if (!slot[j]) {
slot[j] = true;
totalProfit += job.profit;
break;
}
}
}
medium
A. Sorting should be in descending order of profit
B. Slot array size should be maxDeadline, not maxDeadline + 1
C. Inner loop should run from 1 to job.deadline, not backward
D. No error, code is correct
Solution
Step 1: Check sorting order
Sorting by a.profit - b.profit sorts ascending, but we need descending to maximize profit.
Step 2: Verify scheduling logic
The slot array and inner loop correctly find latest free slot before deadline.
Final Answer:
Sorting should be in descending order of profit -> Option A
Quick Check:
Profit descending sort needed [OK]
Hint: Sort jobs by profit descending to maximize total profit [OK]
Common Mistakes:
Sorting ascending by profit
Incorrect slot array size off by one
Loop direction confusion
5. You have jobs with deadlines and profits: Job[] jobs = { new Job('x', 4, 70), new Job('y', 1, 80), new Job('z', 1, 30), new Job('w', 2, 100), new Job('v', 3, 40) }; Using the job scheduling algorithm, which jobs will be scheduled to maximize profit and what is the total profit?