Minimum Time to Complete Trips - Problem

You are given an array time where time[i] denotes the time taken by the ith bus to complete one trip.

Each bus can make multiple trips successively; that is, the next trip can start immediately after completing the current trip. Also, each bus operates independently; that is, the trips of one bus do not influence the trips of any other bus.

You are also given an integer totalTrips, which denotes the number of trips all buses should make in total. Return the minimum time required for all buses to complete at least totalTrips trips.

Input & Output

Example 1 — Basic Case
$ Input: time = [1,2,3], totalTrips = 5
Output: 3
💡 Note: At time 3: Bus 0 completes 3/1=3 trips, Bus 1 completes 3/2=1 trip, Bus 2 completes 3/3=1 trip. Total: 3+1+1=5 trips.
Example 2 — Slower Buses
$ Input: time = [2], totalTrips = 1
Output: 2
💡 Note: Only one bus that takes 2 time units per trip. To complete 1 trip, we need exactly 2 time units.
Example 3 — Multiple Fast Buses
$ Input: time = [1,1,1], totalTrips = 10
Output: 4
💡 Note: At time 4: Each of the 3 buses completes 4 trips, totaling 12 trips which exceeds the required 10.

Constraints

  • 1 ≤ time.length ≤ 105
  • 1 ≤ time[i], totalTrips ≤ 107

Visualization

Tap to expand
Minimum Time to Complete Trips INPUT Bus Time Array 1 Bus 0 2 Bus 1 3 Bus 2 Total Trips Needed 5 Time per trip (minutes) 1 min 2 min 3 min time = [1,2,3] totalTrips = 5 ALGORITHM STEPS 1 Binary Search Setup low=1, high=min(time)*trips high = 1 * 5 = 5 2 Count Trips at mid trips = sum(mid/time[i]) 3 Binary Search Logic trips >= target: high=mid trips < target: low=mid+1 4 Return low Minimum time found Search Iterations mid=3: 3/1+3/2+3/3 = 3+1+1 = 5 OK mid=2: 2/1+2/2+2/3 = 2+1+0 = 3 LOW mid=3: trips=5 >= 5 OK Answer: low = 3 FINAL RESULT At time = 3 minutes 0 1 2 3 Bus 0 (1 min): 3 trips Bus 1 (2 min): 1 trip Bus 2 (3 min): 1 trip Total: 3 + 1 + 1 = 5 trips Output 3 OK - 5 trips completed! Key Insight: Binary search on the answer! For any given time T, we can calculate total trips = sum(T / time[i]). If trips >= totalTrips, T might be the answer or we can do better (search left). Time Complexity: O(n * log(min(time) * totalTrips)) where n = number of buses. TutorialsPoint - Minimum Time to Complete Trips | Binary Search Approach
Asked in
Amazon 15 Google 12 Microsoft 8 Facebook 6
23.4K Views
Medium Frequency
~25 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen