Step 2: Schedule jobs in latest free slot before deadline
Schedule A at slot 1 (0-based), C at slot 0, E at slot 2. D and B cannot be scheduled as slots 0 and 1 are taken.
Final Answer:
['A', 'C', 'E'] -> Option D
Quick Check:
Jobs scheduled = ['A', 'C', 'E'] [OK]
Hint: Sort by profit, assign latest free slot before deadline [OK]
Common Mistakes:
Scheduling jobs in arrival order instead of profit order
Assigning earliest slot instead of latest free slot
Ignoring slot availability and deadlines
4. Identify the bug in this Rust code snippet for job scheduling with deadlines:
fn schedule_jobs(jobs: &mut Vec<(char, usize, usize)>) -> Vec<char> {
jobs.sort_by(|a, b| b.2.cmp(&a.2));
let max_deadline = jobs.iter().map(|j| j.1).max().unwrap_or(0);
let mut slots = vec![false; max_deadline];
let mut result = Vec::new();
for job in jobs.iter() {
for slot in 0..job.1 {
if !slots[slot] {
slots[slot] = true;
result.push(job.0);
break;
}
}
}
result
}
medium
A. Jobs are sorted by profit ascending instead of descending
B. Inner loop should iterate slots in reverse order to assign latest slot
C. Result vector should store job profits instead of IDs
D. Slots vector size is incorrect, should be max_deadline + 1
Solution
Step 1: Check sorting order
Jobs are sorted by profit descending (b.2.cmp(&a.2)), which is correct to prioritize high-profit jobs.
Step 2: Check slot assignment loop
The loop iterates from 0 to deadline-1, assigning the earliest available slot. The correct approach assigns the latest free slot before the deadline to leave earlier slots for future jobs with tighter deadlines, so the loop should be reversed using (0..job.1).rev().
Final Answer:
Inner loop should iterate slots in reverse order to assign latest slot -> Option B
Quick Check:
Assign latest free slot by looping backwards [OK]
Hint: Loop slots backward to assign latest free slot [OK]
Common Mistakes:
Assigning earliest slot instead of latest free slot
Using wrong slot vector size (off-by-one)
Storing wrong data in result vector
5. Given jobs with deadlines and profits: A(4, 70), B(1, 80), C(1, 30), D(2, 100), E(3, 40), how many jobs can be scheduled to maximize profit and what is the total profit?
Use the job scheduling with deadlines approach.
Step 2: Schedule jobs in latest free slot before deadline
Schedule B at slot 0 (deadline 1), D at slot 1 (deadline 2), E at slot 2 (deadline 3), A at slot 3 (deadline 4). C cannot be scheduled as slot 0 is taken.
Step 3: Calculate total profit
Profits: B(80) + D(100) + E(40) + A(70) = 290
Final Answer:
4 jobs, total profit 290 -> Option A
Quick Check:
4 jobs scheduled, profit = 290 [OK]
Hint: Sort by profit, assign latest free slot before deadline [OK]
Common Mistakes:
Scheduling fewer jobs than possible
Ignoring slot availability and deadlines
Adding profits of unscheduled jobs
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.