Greedy Algorithms8 sections · 316 units
Open in Course

Job Sequencing - Implementation

The code

function jobSequencing(jobs)
 sort jobs by profit descending
 maxDeadline := max deadline among all jobs
 slots := array of size maxDeadline + 1, all false
 totalProfit := 0
 count := 0
 for each job in jobs
 for slot from job.deadline down to 1
 if not slots[slot] then
 slots[slot] := true
 totalProfit := totalProfit + job.profit
 count := count + 1
 break
 return (count, totalProfit)

Time: O(n2)O(n^2) or O(nlogn)O(n \log n) with Union-Find. Space: O(n)O(n).