Step 2: Schedule jobs in latest available slot before deadline
Job 'a' scheduled at slot 1 (deadline 2), 'c' at slot 0 (deadline 2), 'd' cannot fit before deadline 1 (slot 0 taken), 'b' cannot fit, 'e' scheduled at slot 2 (deadline 3).
Final Answer:
['a', 'c', 'e'] -> Option B
Quick Check:
Scheduled jobs = ['a', 'c', 'e'] [OK]
Hint: Sort by profit, assign latest free slot before deadline [OK]
Common Mistakes:
Scheduling jobs in input order without sorting
Assigning earliest slot instead of latest
Ignoring deadline constraints
4. Identify the bug in the following TypeScript function for job scheduling and select the correct fix.
function scheduleJobs(jobs: Job[]): string[] {
jobs.sort((a, b) => a.profit - b.profit);
const result: (string | null)[] = Array(jobs.length).fill(null);
for (const job of jobs) {
for (let j = job.deadline - 1; j >= 0; j--) {
if (result[j] === null) {
result[j] = job.id;
break;
}
}
}
return result.filter(id => id !== null) as string[];
}
medium
A. Sort jobs by profit descending instead of ascending
B. Initialize result array with zeros instead of null
C. Loop j from 0 to job.deadline - 1 instead of reverse
D. Remove the inner loop and assign jobs directly
Solution
Step 1: Analyze sorting order
Jobs are sorted by profit ascending, which schedules low profit jobs first, reducing total profit.
Step 2: Correct sorting order
Sorting by profit descending ensures high profit jobs are scheduled first for maximum profit.
Final Answer:
Sort jobs by profit descending instead of ascending -> Option A
Quick Check:
Profit descending sort fixes scheduling [OK]
Hint: Sort jobs by descending profit to fix scheduling [OK]
Common Mistakes:
Sorting by ascending profit reduces total profit
Changing loop direction incorrectly
Using zero instead of null for empty slots
5. Given the following jobs with deadlines and profits, what is the maximum total profit achievable by scheduling jobs before their deadlines?
Jobs:
- Job1: deadline = 4, profit = 70
- Job2: deadline = 1, profit = 80
- Job3: deadline = 1, profit = 30
- Job4: deadline = 2, profit = 100
- Job5: deadline = 3, profit = 40
Select the correct maximum profit.