GRDY-P2

The least lateness

Practice 2 of 6Greedy algorithms10 tests

The problem

One machine runs jobs one after another, starting at time 0, with no gaps. Each job is a pair (length, deadline). A job that finishes at time f is late by max(0, f - deadline). Choose the order of the jobs so that the largest lateness is as small as possible, and return that largest lateness.

least_lateness([(3, 6), (2, 2), (1, 9), (4, 8)])
# 1: run (2, 2), (3, 6), (4, 8), (1, 9);
# they finish at 2, 5, 9 and 10

Return 0 when every job can finish on time, and for an empty list. Lengths are at least 1; deadlines are at least 0.

Limits

  • Up to 200,000 jobs. Trying every order is impossible; aim for O(n log n).

Builds on GRDY-2 Exchange arguments.

Continue on a laptop

Practice runs Python in the browser and needs a keyboard and a wider screen. Read the problem and open hints here, then write your solution on a laptop. Progress is saved per browser for now, so hints opened here stay on this device.

Need a hint?0 of 3 opened

  1. Hint 1Nudge
  2. Hint 2Approach Open hint 1 first
  3. Hint 3Pseudocode Open hint 2 first
  4. Worked solutionlast resort Opens after all 3 hints
Python waits for a wider screensolution.py

Ctrl + Enter runs the tests. Tab indents; press Esc, then Tab, to leave the editor.

10 tests, not run yet
Test results
#TestResultReads · time
1The exampleNot run
2All on timeNot run
3No jobsNot run
4One late jobNot run
5Shortest first is wrongNot run
6Least slack first is wrongNot run
7Same deadlinesNot run
8Deadline 0Not run
9Nine jobsNot run
10200,000 jobsNot run