Ride-hailing app~15 min2s · 256 MBtarget O(n log n) time, O(n) spaceclassic twin: lc-646greedy · sorting
You work on a ride-hailing app. A driver has a list of pre-booked rides. Each ride has a pickup minute and a drop-off minute, counted from the start of the shift.
The driver needs at least one minute between a drop-off and the next pickup, so the next pickup must come strictly after the last drop-off. Your team lead asks: "What is the most rides one driver can serve one after another?"
Write longest_chain(bookings).
bookings[i] is a pair [pickup, dropoff] with pickup < dropoff.Input: bookings = [[5, 9], [1, 3], [3, 6], [7, 8], [10, 12]]
Output: 3Sort by drop-off minute: [1, 3], [3, 6], [7, 8], [5, 9], [10, 12]. Take a ride when its pickup is strictly after the last drop-off taken.
| Ride | Last drop-off | Pickup strictly after it? | Chain length |
|---|---|---|---|
[1, 3] |
none | yes | 1 |
[3, 6] |
3 | no (3 is not above 3) | 1 |
[7, 8] |
3 | yes | 2 |
[5, 9] |
8 | no | 2 |
[10, 12] |
8 | yes | 3 |
The longest chain has 3 rides: [1, 3], [7, 8] and [10, 12].
Input: bookings = [[1, 2], [2, 3]]
Output: 1The second pickup is at minute 2, which is not after minute 2. The driver can serve only one of them.
Input: bookings = [[4, 6], [1, 2], [2, 3]]
Output: 2The rides [1, 2] and [4, 6] form a chain, because 4 is above 2. No chain has 3 rides.
1 ≤ len(bookings) ≤ 100,0000 ≤ pickup < dropoff ≤ 1,000,000,000There can be 100,000 rides. Choosing every subset is 2^100000 possibilities, and testing every pair of rides is 5 billion checks. A sort costs about 1.7 million steps and one pass costs 100,000 more. That fits easily.