KatInterview

Maximize Jobs Completed Before Their Deadlines

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

Last updated

Tests greedy scheduling with deadlines: select and order unit-duration jobs to maximize the count of jobs finished on or before their individual deadlines.

Maximize Jobs Completed Before Their Deadlines

You are given a list of jobs. Each job takes exactly 1 unit of time to complete and has a deadline by which it must finish. Time slots are numbered starting at 1 (so a job with deadline d must be scheduled in a slot ≤ d).

You may schedule at most one job per time slot, and each job may be scheduled at most once. You want to choose a subset of jobs and assign each chosen job to a distinct time slot such that every chosen job finishes on or before its deadline.

Return the maximum number of jobs that can be completed on time.

Details

  • Jobs are given as a list of integers deadlines, where deadlines[i] is the deadline of the i-th job.
  • You do not need to return the schedule itself — only the count of jobs that can be completed on time.
  • If two jobs could both be included but only one fits, prefer the one that leaves more scheduling room for others (this is handled automatically by the greedy strategy; you just return the count).

Constraints

  • 0 ≤ len(deadlines) ≤ 2000
  • 1 ≤ deadlines[i] ≤ 2000
  • All deadlines are positive integers.

Examples

Example 1

Input: max_jobs_on_time([3, 1, 2])

Output: 3

Example 2

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

Output: 1

Example 3

Input: max_jobs_on_time([])

Output: 0

Hints

Hint 1

Sort jobs by deadline in ascending order — greedily scheduling earlier-deadline jobs first avoids blocking later slots unnecessarily.

Hint 2

Keep a counter of how many slots have been used so far. For each job (in deadline order), ask: is the number of slots used so far strictly less than this job's deadline? If yes, schedule it.

Hint 3

This greedy works because every job takes exactly 1 unit of time, so the only question is whether a free slot exists at or before the deadline; sorting ensures we never waste an early slot on a late-deadline job when an early-deadline job still needs it.