KatInterview

Schedule Maximum Jobs Within Deadlines

Greedy & IntervalsAuto-graded · 17 test cases
EasyAuto-gradedGreedy & Intervalsgreedyintervalssorting

Last updated

Tests the classic greedy exchange-argument insight: sort jobs by deadline to maximise the number of unit-length jobs completed before their deadlines.

Schedule Maximum Jobs Within Deadlines

You are given a list of jobs. Each job takes exactly 1 unit of time to complete and has a deadline — the latest time slot by which it must finish.

Time slots are 1-indexed: slot t spans the interval (t-1, t]. A job with deadline d may be scheduled in any slot t where 1 ≤ t ≤ d, provided that slot is not already occupied by another job.

Your goal is to find the maximum number of jobs that can be completed on time if you schedule optimally.

Formally, given a list of deadlines (one per job), return the maximum number of jobs that can be scheduled such that every scheduled job finishes by its deadline.

Constraints

  • 1 ≤ len(deadlines) ≤ 2000
  • 1 ≤ deadlines[i] ≤ 2000
  • All deadlines are positive integers.
  • Multiple jobs may share the same deadline.
  • The order of jobs in the input does not matter.

Examples

Example 1

Input: max_jobs_scheduled([4, 2, 4, 3, 1])

Output: 4

Example 2

Input: max_jobs_scheduled([1, 1, 1])

Output: 1

Example 3

Input: max_jobs_scheduled([3, 3, 3, 3])

Output: 3

Hints

Hint 1

Think about what happens when you try to schedule the job with the earliest deadline first — can an exchange argument show this is never worse than any other order?

Hint 2

After sorting by deadline, greedily assign each job to the latest available slot that is still ≤ its deadline. This avoids unnecessarily blocking earlier slots for later jobs.

Hint 3

A simple boolean array of size max_deadline+1 tracks which slots are occupied; scanning from the job's deadline down to 1 finds the latest free slot in O(d) time.