Python coding

Most tasks done before their deadlines

Each task is [duration, deadline]: it takes duration days of work and counts only if it is finished by day deadline. You start on day 0, work on one task at a time and never pause a task once started. Choose which tasks to do and in what order to finish as many on time as possible; return that number.

A task started on day t finishes on day t + duration, which must not pass its deadline. Durations and deadlines are positive integers, and tasks may be empty.

Besides the tests, one large input (3,000 tasks) with a ~200 ms limit (scaled to your device's speed): brute force won't pass.

  • most_on_time([[3,3],[2,4],[2,5]]) → 2
  • most_on_time([[1,10],[2,2]]) → 2
  • most_on_time([[5,6],[1,6],[1,6],[1,6]]) → 3
Ctrl/⌘ + Enter runs · Tab indents
Hint 1

Whatever set of tasks you finish, doing them in deadline order is never worse. So sort by deadline and decide, task by task, which ones to keep.

Hint 2

Add each task to a running total of days. If the total passes the current deadline, one task has to go: drop the longest one kept so far, using a max-heap of durations.

Hint 3

The trap is skipping the new task when it doesn't fit. Dropping the longest task keeps the same count and frees the most days for the tasks still to come.

Solution and why it works
pythonO(n log n) · O(n)
import heapq

def most_on_time(tasks: list[list[int]]) -> int:
    day, kept = 0, []                    # kept: max-heap of durations (negated)
    for duration, deadline in sorted(tasks, key=lambda t: t[1]):
        day += duration
        heapq.heappush(kept, -duration)
        if day > deadline:               # late: drop the longest task kept, maybe this one
            day += heapq.heappop(kept)
    return len(kept)

Any set you can finish can be done in deadline order (swap two out-of-order tasks and both still make it), so scan by deadline with a max-heap of the durations taken. Add each task; if you are now late, drop the longest one kept, possibly the new one. The count stays the best so far, and the days used are the fewest for that count, leaving the most room for later tasks. O(n log n). The trap: refusing the new task when an earlier, longer one should go.