Problem
Given n
jobs arriving at time 0
, each job i
has a processing time p_i
and a deadline d_i
. A schedule assigns a start time s_i
to each job; the finish time is f_i = s_i + p_i
. The lateness of job i
is l_i = max(0, f_i - d_i)
. Find a schedule that minimizes the maximum lateness L = max_i l_i
.
Examples
Example 1
gantt title Jobs dateFormat YYYY axisFormat %y section Schedule Job3 : 2000, 1y Job1 : 2001, 3y Job2 : 2004, 2y section Deadlines Job3 deadline :milestone, 2003, 0 Job1 deadline :milestone, 2004, 0 Job2 deadline :milestone, 2006, 0
|
|
Solution
The optimal greedy policy is to schedule jobs in non-decreasing order of deadlines (Earliest Deadline First). Below we give the intuition, a precise approach, and code in multiple languages.
Method 1 - Earliest Deadline First
Intuition
Scheduling the job with the earliest deadline next prevents imminent deadlines from being missed. An exchange argument shows that any optimal schedule can be transformed (without increasing maximum lateness) into one that orders jobs by non-decreasing d_i
.
Approach
-
Sort jobs by
deadline
in non-decreasing order. -
Set
time = 0
. -
For each job in sorted order:
-
Assign
start = time
andfinish = time + p
. -
Compute
lateness = max(0, finish - deadline)
and updateL = max(L, lateness)
. -
Set
time = finish
.
- Return
L
(maximum lateness) and the schedule if required.
Edge cases:
- If
n == 0
returnL = 0
. - Jobs with equal deadlines may be ordered arbitrarily; the maximum lateness is identical for any order among equal-deadline jobs.
Code
|
|
|
|
|
|
|
|
Complexity
- ⏰ Time complexity:
O(n log n)
for sorting then
jobs; the scan isO(n)
, so totalO(n log n)
. - 🧺 Space complexity:
O(1)
extra space beyond input (orO(n)
if the sort implementation requires auxiliary space).