Problem Description
Given an array time, where time[i] represents the time needed by the iᵗʰ bus to complete one trip, and an integer totalTrips, the objective is to determine the minimum time required so that all buses together can complete at least totalTrips trips. Each bus can perform trips continuously one after another, and the trips on one bus are independent of the trips on another.
Key Insights
- The total number of trips completed up to a given time t is the sum of t // time[i] for each bus.
- The relationship between time t and the total trips is monotonic (non-decreasing); if t is enough to satisfy the condition, any time greater than t will also satisfy it.
- Binary search over the time makes it possible to efficiently find the minimum time t such that the number of trips is at least totalTrips.
- Set the initial boundaries for binary search: left bound can be 1, and right bound can be max(time) * totalTrips.
Space and Time Complexity
Time Complexity: O(n * log(max(time) * totalTrips)), where n is the length of the time array. Space Complexity: O(1) (excluding the input array storage).
Solution
We use a binary search approach on the time domain. The key idea is to define a helper function that, for a given candidate time t, calculates the total number of trips all buses can complete, which is sum(t // time[i]). With this helper, perform binary search between 1 and max(time) * totalTrips. If the total trips for a candidate time is greater than or equal to totalTrips, then explore lower times, otherwise, move the lower bound upward. This approach efficiently narrows down the minimum time required.