LeetCode 2187. Minimum Time to Complete Trips
原题链接在这里:https://leetcode.com/problems/minimum-time-to-complete-trips/
题目:
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.
Constraints:
1 <= time.length <= 105
1 <= time[i], totalTrips <= 107
题解:
For a given time, we could calculate how many trips we could finish.
We could guess a time, if the calculate trips count < totalTrips, then l = mid + 1. Otherwise, r = mid.
Time Complexity: O(nlogm). n = time.length. m = min * totalTrips.
Space: O(1).
AC Java:
1 class Solution { 2 public long minimumTime(int[] time, int totalTrips) { 3 if(time == null || time.length == 0 || totalTrips <= 0){ 4 return 0; 5 } 6 7 int n = time.length; 8 long min = time[0]; 9 for(int i = 0; i < n; i++){ 10 min = Math.min(min, time[i]); 11 } 12 13 long l = 0; 14 long r = min * totalTrips; 15 while(l < r){ 16 long mid = l + (r - l) / 2; 17 if(count(time, mid) < totalTrips){ 18 l = mid + 1; 19 }else{ 20 r = mid; 21 } 22 } 23 24 return l; 25 } 26 27 private long count(int[] time, long mid){ 28 long res = 0; 29 for(int t : time){ 30 res += mid / t; 31 } 32 33 return res; 34 } 35 }