Maximum profit from unit-time tasks with deadlines
I was asked this
No reports yet. Sign in to say where you were asked it.
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 ift + 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.
-
deadlineandprofitare 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
0be scheduled? - Is a deadline of
0a 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 onlynseconds 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 thann, 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
Sign in to see the worked answer
The full answer, chapter by chapter, with what interviewers expect at each level. New accounts get 5 credits: each one unlocks a question for good.
What the labs asked this week
A weekly email of what OpenAI, Anthropic and the other top AI labs asked engineers, round by round.
Sign in to submit your code; every attempt is kept here.
