Sub topic 4
Job Sequencing with Deadlines and Profits
Problem model
Assume you know asymptotic notation, sorting, arrays, and the basic greedy-choice idea. In this problem, every job:
- takes exactly one time slot,
- has an integer deadline,
- earns a profit only if it finishes by its deadline.
Only one job can run in each slot. The goal is to maximize total profit, not the number of jobs.
For example, job A(2, 100) has deadline 2 and profit 100. It can run in slot 1 or slot 2. A job with deadline 0 cannot be scheduled.
Greedy strategy
Use these steps:
- Sort jobs by decreasing profit.
- For each job, scan backward from its deadline.
- Put the job in the latest free slot at or before that deadline.
- Skip the job if no such slot exists.
Using the latest available slot preserves earlier slots for jobs with tighter deadlines.
def schedule_jobs(jobs):
# Each job is (name, deadline, profit).
jobs = sorted(jobs, key=lambda job: job[2], reverse=True)
slot_count = max((deadline for _, deadline, _ in jobs), default=0)
slots = [None] * (slot_count + 1) # Slot 0 is unused.
total_profit = 0
for name, deadline, profit in jobs:
latest = min(deadline, slot_count)
for slot in range(latest, 0, -1):
if slots[slot] is None:
slots[slot] = name
total_profit += profit
break
return [job for job in slots[1:] if job is not None], total_profit
jobs = [
("A", 2, 100),
("B", 1, 19),
("C", 2, 27),
("D", 1, 25),
("E", 3, 15),
]
print(schedule_jobs(jobs)) # (['A', 'C', 'E'], 142)For the example, A is placed in slot 2, C in slot 1, and E in slot 3. The total profit is 142.
Why the strategy works
The first greedy choice is the unscheduled job with the greatest profit. If an optimal schedule contains a different job in a slot that can hold this job, exchange the two jobs. The schedule remains feasible because the greedy job has no later deadline requirement than that slot, and its profit is at least as large. Repeating this exchange produces an optimal schedule containing the greedy choice.
The “latest free slot” rule is also safe. Moving a selected job later leaves earlier positions available for jobs with smaller deadlines.
Complexity and exam checks
Let n be the number of jobs and D the largest deadline.
| Step | Cost |
|---|---|
| Sort by profit | O(n log n) |
| Scan slots | O(nD) |
| Total with direct scanning | O(n log n + nD) |
| Extra space | O(D) |
A disjoint-set union structure can find the latest available slot faster, reducing slot allocation to near-constant amortized time after sorting.
Exercise
Jobs are A(2, 50), B(1, 60), and C(2, 40). Which jobs are selected and what is the maximum profit?
Show answer
Sort by profit: B, A, C. Place B in slot 1 and A in slot 2. C cannot fit, so the maximum profit is 110.