[LeetCode] 2187. 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
完成旅途的最少时间。
给你一个数组 time ,其中 time[i] 表示第 i 辆公交车完成 一趟旅途 所需要花费的时间。每辆公交车可以 连续 完成多趟旅途,也就是说,一辆公交车当前旅途完成后,可以 立马开始 下一趟旅途。每辆公交车 独立 运行,也就是说可以同时有多辆公交车在运行且互不影响。
给你一个整数 totalTrips ,表示所有公交车 总共 需要完成的旅途数目。请你返回完成 至少 totalTrips 趟旅途需要花费的 最少 时间。
来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/minimum-time-to-complete-trips
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
思路
思路是二分法,而且是在答案上二分。
题意很好理解,让你找一个最少完成 totalTrips 趟旅途所花的时间。因为时间是线性的,所以我们可以利用二分的性质快速找到一个合适的时间,二分的下界是 1,上界可以取一个足够大的数字,或者有的做法是找出速度最快的公交车,看他完成 totalTrips 趟旅途的所需时间。
因为我们二分法分的是最后的答案 - 完成 totalTrips 趟旅途所需的时间,所以我们判断 mid 到底往左还是往右是需要判断在 mid 时间内,所有公交车能完成的旅途是多少,如果大于 totalTrips,则说明当前速度太快,速度可以减少一些, right = mid;反之 left = mid + 1。
复杂度
时间O(nlogn)
空间O(1)
代码
Java实现
class Solution {
public long minimumTime(int[] time, int totalTrips) {
long left = 1;
long right = (long) 1e18;
while (left < right) {
long mid = left + (right - left) / 2;
if (helper(time, mid, totalTrips) >= totalTrips) {
right = mid;
} else {
left = mid + 1;
}
}
return left;
}
private long helper(int[] bus, long time, int totalTrips) {
int n = bus.length;
long res = 0;
for (int i = 0; i < n; i++) {
res += time / bus[i];
if (res >= totalTrips) {
break;
}
}
return res;
}
}