Ride-hailing app~25 min2s · 256 MBtarget O(n log T) time, O(1) spaceclassic twin: lc-2187binary-search-answer
A ride-hailing app has drivers who each work non-stop. Driver i needs trip_times[i] minutes for one trip and starts the next trip right away. Different drivers work at the same time.
The app has a number of trips to serve in total. What is the smallest number of minutes after which the drivers together can have finished at least that many trips?
Write min_time(trip_times, trips).
i finishes one trip every trip_times[i] minutes. After T minutes, the driver has finished T // trip_times[i] whole trips. A trip that is not finished does not count.T such that the drivers together have finished at least trips trips.Input: trip_times = [1, 2, 3], trips = 5
Output: 3The fastest driver alone needs 1 × 5 = 5 minutes, so the answer is at most 5. After T minutes, the drivers have finished T // 1 + T // 2 + T // 3 trips. Search the window [lo, hi), where hi always works.
| Step | lo | hi | mid | trips done by minute mid | Decision |
|---|---|---|---|---|---|
| 1 | 1 | 5 | 3 | 3 + 1 + 1 = 5 | 5 >= 5, enough, so hi = 3 |
| 2 | 1 | 3 | 2 | 2 + 1 + 0 = 3 | 3 < 5, not enough, so lo = 3 |
| end | 3 | 3 | the earliest time is 3 minutes |
Input: trip_times = [5], trips = 1
Output: 5One driver, one trip: the answer is 5 minutes, the top of the window, 5 × 1.
Input: trip_times = [10, 10, 10, 10], trips = 8
Output: 20Four equal drivers each finish a trip every 10 minutes. By minute 20, each has finished 2 trips, which makes 8.
1 ≤ trip_times.length ≤ 100,0001 ≤ trip_times[i] ≤ 1,000,000 minutes for one trip1 ≤ trips ≤ 1,000,000,000Trying every time from 1 minute up, with a pass over the drivers each time, costs about n × (the answer) steps. The answer can be 10^9 minutes or more, so that is beyond 10^14. One count costs n steps. A binary search over the time, up to 10^15, needs about 50 counts, so about 5 × 10^6 steps.