
Problem Statement
Given an array titled time
, each item within it (e.g., time[i]
) represents the duration required by the i-th
bus to finish one full trip. Every bus can perform several consecutive trips instantly following the conclusion of a previous trip, and every bus functions autonomously meaning their operations do not interfere with each other.
Another integer provided is totalTrips
, indicating the collective number of trips that all buses must fulfill. The objective is to determine the minimal time necessary for all the buses to complete at least the specified number of trips mentioned as totalTrips
.
Examples
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
Approach and Intuition
To solve this problem, one can use a binary search mechanism on the time. Here's a stepwise breakdown of how we could approach finding the minimum time required to complete the totalTrips
using all the buses provided:
Establish the possible range for the minimum time.
- The lower limit is the smallest value in the
time
array (best-case scenario where all trips are exactly one time unit). - The upper limit would be the largest value in the
time
multiplied bytotalTrips
. It represents the worst-case scenario where the slowest bus alone would attempt all trips.
- The lower limit is the smallest value in the
Iterate using binary search:
- Calculate the middle point of your current time range.
- For each bus, determine how many complete trips it could achieve within this "mid" amount of time.
- Sum all these trips.
If the summed trips reach or exceed
totalTrips
:- Reduce the search range by adjusting the high boundary of the time to mid-point since it's possible to complete the trips in equal or less time.
If the summed trips are less than
totalTrips
:- Increase the lower boundary of the time to mid-point + 1 because more time is required for all the buses to complete the trips.
Continue the search until the range converges:
- The process narrows down to the precise minimal time needed as the low and high boundaries of the time converge.
This binary search approach efficiently handles even large numbers due to its logarithmic time complexity, making it feasible within the constraints provided.
Solutions
- C++
- Java
- Python
class Solution {
public:
bool sufficientTripTime(vector<int>& durations, long long maxDuration, int requiredTrips) {
long long tripsCount = 0;
for (int duration : durations) {
tripsCount += maxDuration / duration;
}
return tripsCount >= requiredTrips;
}
long long minTimeToCompleteTrips(vector<int>& durations, int requiredTrips) {
long long minTime = 1, maxTime = 1LL * *max_element(durations.begin(), durations.end()) * requiredTrips;
while (minTime < maxTime) {
long long middleTime = (minTime + maxTime) / 2;
if (sufficientTripTime(durations, middleTime, requiredTrips)) {
maxTime = middleTime;
} else {
minTime = middleTime + 1;
}
}
return minTime;
}
};
You want to find the minimum time required to complete a given number of trips using vehicles with specified durations for single trips. Below is the implementation in C++ that will achieve this.
Start by writing the helper function
sufficientTripTime
, which checks if a given maximum duration allows all trips to be made. It calculates the total number of trips that can be completed within this time by iterating over each vehicle's duration, adding up how many trips each can make within themaxDuration
.Implement the main function
minTimeToCompleteTrips
to determine the minimum required time to complete the specified number of trips using binary search:- Initialize
minTime
to 1 andmaxTime
to the product of the maximum single trip duration and the number of required trips. - Execute a binary search on time:
- Calculate the midpoint
middleTime
as the average ofminTime
andmaxTime
. - Use the
sufficientTripTime
function to check if the currentmiddleTime
is sufficient to complete the required trips. - If true, update
maxTime
tomiddleTime
to search for a possibly smaller valid time. - If false, adjust
minTime
tomiddleTime + 1
to omit non-feasible durations.
- Calculate the midpoint
- The search loop continues until
minTime
equalsmaxTime
, the point at whichminTime
will represent the minimum time required to complete the trips.
- Initialize
This binary search approach efficiently narrows down the minimal time needed by reducing the search range, leveraging the fact that if a certain time is sufficient to complete the trips, any time longer than that will also suffice (and vice versa).
class Solution {
public boolean canCompleteTrips(int[] durations, long maxDuration, int requiredTrips) {
long trips = 0;
for (int duration : durations)
trips += maxDuration / duration;
return trips >= requiredTrips;
}
public long findLeastTime(int[] durations, int requiredTrips) {
int longest = 0;
for (int t : durations) {
longest = Math.max(longest, t);
}
long low = 1, high = (long) longest * requiredTrips;
while (low < high) {
long mid = (low + high) / 2;
if (canCompleteTrips(durations, mid, requiredTrips)) {
high = mid;
} else {
low = mid + 1;
}
}
return low;
}
}
The solution presented in Java for the problem of finding the minimum time to complete a specified number of trips using different durations focuses on an efficient approach using binary search.
- The solution comprises two primary functions:
canCompleteTrips(int[] durations, long maxDuration, int requiredTrips)
verifies if the total required trips can be accomplished within the provided maximum duration.findLeastTime(int[] durations, int requiredTrips)
calculates the minimum time to complete the required trips.
- The
canCompleteTrips
method computes the total number of trips possible by iterating through each trip duration and summing how many trips can be made within themaxDuration
using integer division. - In the
findLeastTime
method:- Identify the maximum trip duration in the array, to establish a reasonable upper limit for the binary search.
- Set initial boundaries for binary search;
low
starts at 1 andhigh
is calculated as the product of the longest duration and required trips. - Through binary search, determine the smallest maximum time interval (
low
) where the number of trips meets or exceeds the required count.
This binary search strategy efficiently narrows down the potential minimal duration necessary to meet the required number of trips, ensuring an optimal and quick solution.
class Solution:
def findMinTime(self, durations: List[int], requiredTrips: int) -> int:
# Set initial search boundaries
low, high = 1, max(durations) * requiredTrips
def sufficientTime(mid_time):
current_trips = 0
for duration in durations:
current_trips += mid_time // duration
return current_trips >= requiredTrips
# Perform binary search to find the lowest sufficient time
while low < high:
midpoint = (low + high) // 2
if sufficientTime(midpoint):
high = midpoint
else:
low = midpoint + 1
return low
The following Python3 solution addresses the problem of finding the minimum time required to complete a specified number of trips using different vehicles that operate at varying speeds. This problem is efficiently solved using a combination of binary search and a helper function.
The findMinTime
method accepts two parameters: an array of integers durations
where each integer represents the time taken by a vehicle to complete one trip, and an integer requiredTrips
which is the total number of trips that must be completed across all vehicles.
Here’s a stepwise explanation of the code:
Define the search range's initial bounds:
low
is initialized as 1 — the minimum conceivable time is often considered as one time unit since no trip can be completed in zero time.high
is initialized to the product of the maximum single trip duration indurations
andrequiredTrips
— this assumes a worst-case scenario where the slowest vehicle might conceivably take all the trips sequentially, thus providing an upper bound on the search space.
Implement the
sufficientTime(mid_time)
helper function to determine whether all required trips can be completed withinmid_time
:- Initialize
current_trips
to zero. - Iterate through the
durations
array, summing up the number of trips that each vehicle can complete withinmid_time
. - Return a boolean indicating if the number of computed trips is adequate (
>= requiredTrips
).
- Initialize
Conduct a binary search using these boundaries to home in on the minimal time:
- While the lower bound (
low
) is less than the upper (high
), calculate the midpoint and check if it suffices viasufficientTime(midpoint)
. - If it is sufficient, adjust the upper bound (
high
) to the midpoint, effectively narrowing down the potential minimum time. Otherwise, adjust the lower bound to just above the midpoint (low = midpoint + 1
).
- While the lower bound (
Once the loop completes,
low
will be at the minimal sufficient time value, and it is returned.
This approach is efficient, leveraging a binary search that typically completes in logarithmic time relative to the size of the input, avoiding the need for brute force examination of every possible time duration from 1
to high
. Armed with this solution, you have the capacity to optimize travel or operational schedules where time efficiency is paramount.
No comments yet.