1494. Latest Departure Plan
A commuter travels along stops 0, 1, ..., legs, where legs is the length of departures. Leg i runs from stop i to stop i+1: shuttles on that leg leave at the times listed in departures[i] (sorted ascending, rows may differ in length) and the ride takes rideTime[i]. Arriving at a stop at time T, the commuter boards the earliest shuttle on the next leg that leaves at time T or later; if none is left, the trip fails. The commuter starts at stop 0 at some integer time t with 0 <= t <= deadline.
Return the latest integer start time t for which the commuter reaches the last stop no later than deadline, or -1 if no start time works. Starting later never helps arrive earlier, so binary search t and simulate each trial with a lower-bound lookup on every leg. Target O(legs * log(deadline) * log(row length)) time and O(1) extra space.
Example 1
- Input:
- departures = [[5,10,20],[16,25],[30,45]]rideTime = [4,6,3]deadline = 40
- Output:
- 10
- Explanation:
Starting at 10: board the 10 departure, arrive at 14, take the 16 departure, arrive at 22, take the 30 departure, arrive at 33 which is within 40; starting at 11 misses the 30 departure and fails.
Example 2
- Input:
- departures = [[0]], rideTime = [1], deadline = 0
- Output:
- -1
- Explanation:
Even leaving at time 0, the only ride ends at time 1, which is after the deadline of 0, so the answer is -1.
Example 3
- Input:
- departures = [[3]], rideTime = [2], deadline = 5
- Output:
- 3
- Explanation:
The single shuttle leaves at 3 and arrives at 5, exactly on the deadline, so starting at 3 is the latest valid start.
Constraints
1 ≤ legs ≤ 100; 1 ≤ departures[i].length ≤ 100 (rows may differ in length, each sorted ascending); 0 ≤ times ≤ 106; 1 ≤ rideTime[i] ≤ 104; 0 ≤ deadline ≤ 2*106
How this problem is judged
- Answers
- Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
- Time per case
- Python 4,000 msC++ 1,000 msJava 2,000 msJavaScript 2,000 msTypeScript 2,000 ms
Expected complexity
- Time
- O(legs * log(deadline) * log(maxRow))
- Space
- O(1)