1737. Latest Common Start
A kitchen must cook n dishes back to back on a single stove. Dish i needs durations[i] minutes of uninterrupted cooking and has to be finished no later than minute deadlines[i] after the stove is first lit. The cook may choose any order for the dishes, but the stove runs without gaps starting at one common minute S (a non-negative integer).
Return the latest start minute S that still lets every dish meet its deadline, or -1 if even starting at minute 0 is not enough. Serving dishes in order of deadline is always best, so S is the minimum over deadline-sorted prefixes of (deadline minus the total duration so far). The answer is unique. Expected: O(n log n) time, O(n) space.
Example 1
- Input:
- durations = [3,2,4], deadlines = [10,6,20]
- Output:
- 4
- Explanation:
In deadline order the finishing offsets are 2, 5, 9 against deadlines 6, 10, 20, leaving slack 4, 5, 11, so the stove can be lit as late as minute 4.
Example 2
- Input:
- durations = [5,5], deadlines = [6,9]
- Output:
- -1
- Explanation:
In deadline order the slacks are 6 - 5 = 1 and 9 - 10 = -1; a negative slack means no start time works, so the answer is -1.
Constraints
1 ≤ n ≤ 1000
1 ≤ durations[i] ≤ 104
1 ≤ deadlines[i] ≤ 109
How this problem is judged
- Answers
- Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
Expected complexity
- Time
- O(n log n)
- Space
- O(n)