KatInterview

Maximize Tasks Completed Before Their Deadlines

Greedy & IntervalsAuto-graded · 17 test cases
MediumAuto-gradedGreedy & Intervalsgreedyintervalsscheduling

Last updated

Tests whether candidates can apply a greedy scheduling-with-deadlines strategy to select and order tasks that maximize the count of on-time completions.

Task Deadline Scheduler

You are managing a single worker who processes tasks one at a time, starting at time 0. Each task has a duration (how many time units it takes) and a deadline (the task must finish by this time, inclusive).

Given a list of tasks, your goal is to choose a subset of tasks and schedule them in some order so that every chosen task finishes on or before its deadline, maximizing the number of tasks completed.

Return the maximum number of tasks the worker can complete on time.

The worker works continuously with no idle time between scheduled tasks (i.e., the next task starts immediately when the previous one ends).

Formal definition

You are given a list tasks where tasks[i] = [duration_i, deadline_i].

  • Find the largest subset S of tasks such that there exists an ordering of S where every task in S finishes on time.
  • Return |S|.

How to determine the optimal subset

Use the classic Earliest Deadline First (EDF) greedy principle:

  1. It is always optimal to schedule chosen tasks in non-decreasing order of deadline.
  2. To maximise the count of tasks completed, iterate over tasks sorted by deadline and greedily include a task if adding it (at the end of the current schedule) still meets its deadline. If including it violates its deadline, skip it — never swap it for an already-accepted task.

This greedy rule (sort by deadline, include if feasible) is provably optimal for maximising the count of on-time tasks when all tasks have equal priority.

Constraints

  • 0 ≤ len(tasks) ≤ 2000
  • 1 ≤ duration_i ≤ 1000
  • 1 ≤ deadline_i ≤ 10000
  • Tasks with equal deadlines may appear; process them in the order they appear in the sorted list (stable sort by deadline, then by duration ascending as a tie-break — this does not affect correctness but ensures a unique greedy trace).
  • An empty task list returns 0.

Examples

Example 1

Input: max_tasks_on_time([[3, 5], [1, 3], [2, 4]])

Output: 2

Example 2

Input: max_tasks_on_time([[5, 4], [2, 6], [1, 2], [3, 9]])

Output: 3

Example 3

Input: max_tasks_on_time([])

Output: 0

Hints

Hint 1

Sort tasks by deadline first — any valid schedule for a chosen subset can be rearranged into EDF order without causing any previously feasible task to miss its deadline (exchange argument).

Hint 2

Keep a running total of time elapsed; when you consider the next task in deadline order, check whether current_time + duration ≤ deadline before including it.

Hint 3

You do not need to swap or replace already-accepted tasks — simply skipping infeasible tasks while iterating in deadline order is sufficient to maximise the count.