Table of Contents
Problem Statement
source: https://leetcode.com/problems/minimum-time-to-complete-trips/description/
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.
Example 1:
Input: time = [1,2,3], totalTrips = 5
Output: 3
Explanation:
- At time t = 1, the number of trips completed by each bus are [1,0,0].
The total number of trips completed is 1 + 0 + 0 = 1. - At time t = 2, the number of trips completed by each bus are [2,1,0].
The total number of trips completed is 2 + 1 + 0 = 3. - At time t = 3, the number of trips completed by each bus are [3,1,1].
The total number of trips completed is 3 + 1 + 1 = 5.
So the minimum time needed for all buses to complete at least 5 trips is 3.
Example 2:
Input: time = [2], totalTrips = 1
Output: 2
Explanation:
There is only one bus, and it will complete its first trip at t = 2.
So the minimum time needed to complete 1 trip is 2.
Java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
class Solution { public long minimumTime(int[] time, int totalTrips) { int maxTime = Integer.MIN_VALUE; for(int i=0;i<time.length;i++){ maxTime = Math.max(maxTime, time[i]); } //Binary Search long lo = 1; long hi = (long) maxTime * totalTrips; while(lo < hi){ long mid = lo + (hi-lo)/2; if(isPossible(time, totalTrips, mid)){ hi = mid; } else { lo = mid+1; } } return lo; } //see if it is possible to complete totalTrips in time t private boolean isPossible(int[] time, int totalTrips, long t){ long sum = 0; for(int i=0;i<time.length;i++){ sum = sum + t/time[i]; } return (sum >= totalTrips); } } |
Python
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
class Solution: def minimumTime(self, time: List[int], totalTrips: int) -> int: upper = min(time) * totalTrips lower = 1 def checkTripCount(t): trips = 0 for ti in time: trips += t//ti if trips >= totalTrips: return True return False def binSearch(low, high): if low >= high: return low mid = (low + high) >> 1 if checkTripCount(mid): # mid satisfies the totalTrips count high = mid else: low = mid + 1 return binSearch(low, high) return binSearch(lower, upper) |