← Questions

Maximum profit from unit-time tasks with deadlines

0
AirbnbCoding

A coding interview question asked at Airbnb. It tests greedy, heap and scheduling.

You are given a list of tasks. Each task is a list of three strings: [name, deadline, profit].

  • Every task takes exactly 1 second, and only one task can run at a time.
  • Time starts at 0. A task that runs during second [t, t+1) is on time only if t + 1 <= deadline.
  • You earn a task's profit only if it finishes on time. Tasks you do not schedule earn nothing.

Implement:

def max_task_rewards(tasks: list[list[str]]) -> tuple[int, list[str]]:
    ...

Return the maximum total profit and the names of the chosen tasks in the order they run. Order tasks with the same deadline by name so the answer is deterministic.

Constraints

  • 0 <= len(tasks) <= 10^5
  • Task names are unique.
  • deadline and profit are integer strings; 0 <= deadline <= 10^9, 0 <= profit <= 10^9.

Example 1

tasks = [["build", "2", "40"], ["lint", "1", "10"], ["test", "2", "30"], ["ship", "3", "5"]]
-> (75, ["build", "test", "ship"])

Only two tasks fit before second 2, so build and test beat lint. ship still fits in the third second.

Example 2

tasks = [["a", "1", "3"], ["b", "1", "8"], ["c", "0", "50"]]
-> (8, ["b"])

c can never finish on time, and only one of a and b fits in the first second.

Clarifying questions

  • When two different sets give the same best profit, which set should be returned?
  • Should a task with profit 0 be scheduled?
  • Is a deadline of 0 a task that can never run? (Yes.)
  • Are the strings always valid integers?

What a strong answer covers

  • Parses the strings to integers, and caps each deadline at n, since only n seconds can ever be used.
  • Picks the set with a greedy: sort by deadline and keep a min-heap of profits, dropping the smallest whenever the heap holds more tasks than the current deadline. Or sort by profit and put each task in the latest free second with union-find.
  • That is O(n log n). Explains why the greedy is optimal (an exchange argument).
  • Orders the chosen tasks by deadline, then by name, which is always a valid schedule.
  • Tests both examples, deadline 0, all deadlines equal, deadlines far larger than n, and the empty list.

Follow-ups

  • Tasks take different amounts of time: why the greedy breaks, and a DP for small inputs.
  • Several machines run tasks in parallel.
  • Tasks also have a release time.
  • Return the start second of each task.

Where it's asked

What it tests

greedy · heap · scheduling · sorting

Write and test your solution herePython in your browser, the question's tests level by level, every submission kept for you.Sign in to start coding