Parcel-delivery app~30 min2s · 256 MBtarget O(n + m) time, O(n + m) spaceclassic twin: lc-2050topological-sort · dp
A new warehouse is being fitted out with numbered tasks, such as laying floors, mounting racks and wiring lights. Each task takes a number of days. A task can start only after every task it needs is done.
Many crews work at the same time, so any number of tasks may run in parallel. You want the earliest day on which every task is done, counting from day 0.
Write earliest_finish(durations, needs).
durations[i] is the number of days task i takes. The tasks are numbered from 0 to len(durations) - 1.needs[i] is [a, b]: task b can start only after task a is done. A line may repeat.Input: durations = [3, 2, 4, 1, 5], needs = [[0,2],[1,2],[2,3],[2,4]]
Output: 12Tasks 0 and 1 start on day 0. Task 2 needs both, so it starts when the slower one is done, on day 3. Tasks 3 and 4 need task 2.
| Task | Duration | Starts on day | Done on day |
|---|---|---|---|
| 0 | 3 | 0 | 3 |
| 1 | 2 | 0 | 2 |
| 2 | 4 | 3 | 7 |
| 3 | 1 | 7 | 8 |
| 4 | 5 | 7 | 12 |
The last task is done on day 12, so the answer is 12. The chain 0, 2, 4 takes 3 + 4 + 5 = 12 days.
Input: durations = [2, 2, 2], needs = [[1,2],[2,1]]
Output: -1Tasks 1 and 2 each need the other, so neither can start. The answer is -1, although task 0 could be done.
Input: durations = [4, 9, 2], needs = []
Output: 9No task needs another, so all start on day 0. The slowest takes 9 days.
1 ≤ durations.length ≤ 50,000, and 1 ≤ durations[i] ≤ 10,0000 ≤ needs.length ≤ 100,000, and each line is [a, b] with 0 ≤ a, b < durations.lengthRecursing over all prerequisites without remembering results repeats the same task many times. A layered plan with 25,000 layers of two tasks repeats it about 2^25000 times. Taking each task once and passing its finish day forward costs n + m, about 150,000 steps.