KatInterview

Schedule Maximum Jobs Before Their Deadlines

Greedy & IntervalsAuto-graded · 16 test cases
MediumAuto-gradedGreedy & Intervalsgreedyschedulingintervals

Last updated

Tests greedy scheduling with deadlines: select the maximum number of unit-length jobs, each with a profit and deadline, maximizing total profit within deadline slots.

Schedule Maximum Profit Jobs

You are managing a single-machine job queue. There are n jobs, each taking exactly one unit of time to complete. Time slots are numbered 1, 2, 3, …. Each job has:

  • A deadline d (the job must finish at or before time slot d)
  • A profit p (earned only if the job is scheduled before or on its deadline)

The machine can process at most one job per time slot.

Your task is to select a subset of jobs and assign each to a distinct time slot ≤ its deadline, maximizing total profit. Return the maximum total profit achievable and the number of jobs scheduled.

Function Signature

def schedule_jobs(jobs: list[list[int]]) -> list[int]:
  • jobs: a list of [deadline, profit] pairs.
  • Returns [max_profit, num_jobs_scheduled].

How the greedy works

Sort jobs by profit descending. For each job (greediest first), try to assign it to the latest available slot that is ≤ its deadline. If such a slot exists, schedule it; otherwise skip.

Constraints

  • 0 ≤ len(jobs) ≤ 2000
  • 1 ≤ deadline ≤ 1000
  • 0 ≤ profit ≤ 10^6
  • If jobs is empty, return [0, 0].
  • Profits are not necessarily distinct.
  • Multiple jobs may share the same deadline.

Examples

Example 1

Input: schedule_jobs([[4, 20], [1, 10], [1, 40], [1, 30]])

Output: [60, 2]

Example 2

Input: schedule_jobs([[2, 100], [1, 19], [2, 27], [1, 25], [3, 15]])

Output: [142, 3]

Example 3

Input: schedule_jobs([])

Output: [0, 0]

Hints

Hint 1

Sort jobs by profit in descending order so you always try to place the most valuable job first.

Hint 2

Use a boolean array of size (max_deadline + 1) to track which time slots are still free; for each job scan from its deadline down to slot 1 for the latest free slot.

Hint 3

If no free slot ≤ the job's deadline exists, skip that job entirely and move on to the next.