Algorithms · Visualized
Job Sequencing
Greedy
Make the locally optimal choice at each step, hoping it leads to a globally optimal solution.
Given jobs with deadlines and profits, and only one job can run per time slot, schedule jobs to maximize total profit. Time: O(n log n + n × d), where d is the max deadline average, O(n²) in the naive slot-search version; can be optimized with a disjoint-set union to O(n log n) worst; space: O(d) — the slot array.
Big-O: Works when the problem has optimal substructure + greedy-choice property — e.g. intervals, Huffman, fractional knapsack.
Job Sequencing (with Deadlines)
GreedyGiven jobs with deadlines and profits, and only one job can run per time slot, schedule jobs to maximize total profit. The greedy approach: sort jobs by profit descending, and for each job, greedily place it in the latest available time slot at or before its deadline (keeping earlier slots free for jobs with tighter deadlines).
How Job Sequencing Works
- Sort jobs in descending order of profit.
- Create a set of empty time slots, one for each day up to the maximum deadline among all jobs.
- For each job (highest profit first), try to place it in the latest available slot at or before its deadline.
- If a free slot is found at or before the deadline, assign the job there and add its profit to the total.
- If no free slot is available before its deadline, skip the job. Continue for all jobs — the assigned slots represent the optimal schedule.
Job Sequencing Worked Example
Input: [{id: a, deadline: 4, profit: 20}, {id: b, deadline: 1, profit: 10}, {id: c, deadline: 1, profit: 40}, {id: d, deadline: 1, profit: 30}]
Sorted by profit: c(40,d1), d(30,d1), a(20,d4), b(10,d1). Place c in slot1 (latest free ≤1). Place d: slot1 taken, no slot ≤1 free → skip. Place a: latest free ≤4 is slot4 → place there. Place b: slot1 taken, no other slot ≤1 → skip. Scheduled: c and a, total profit = 40+20 = 60.
| job | deadline | profit | |
|---|---|---|---|
| c | c | 1 | 40 |
| d | d | 1 | 30 |
| a | a | 4 | 20 |
| b | b | 1 | 10 |
def job_sequencing(jobs):
# jobs: (id, deadline, profit); max profit, each job takes 1 slot
jobs.sort(key=lambda j: j[2], reverse=True)
n = max(j[1] for j in jobs)
slots = [False] * (n + 1)
out, total = [], 0
for jid, d, p in jobs:
s = min(d, n)
while s >= 1 and slots[s]:
s -= 1
if s >= 1:
slots[s] = True
out.append(jid)
total += p
return out, totalBehind the Scenes Execution
Press ▶ Run in the visualizer — the call stack, registers and memory will replay here in sync with the code, line by line.
Job Sequencing Time & Space Complexity
When to Use Job Sequencing
- CPU/task scheduling with deadlines, prioritizing maximum reward.
- Any 'one resource per time unit, maximize total value' scheduling scenario.
Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Keep the momentum going
Step through a related structure, pattern or course — the ideas reinforce each other and stick faster.