Minimum Time to Complete Trips - Binary Search
- Get link
- X
- Other Apps
By
Anna An
on
Solution: Binary Search
Upper bound set to 10^7 * 10^7, since time[i], totalTrips <= 10^7.
Binary search for the minimum time where each bus can complete at least 'time' number of trips.
Time Complexity: O(n log(10^14))
Space Complexity: O(1)
var minimumTime = function(time, totalTrips) {
let low = 1, high = 100000000000000 + 1;
while (low < high) {
let mid = Math.floor((low + high) / 2);
if (isEnough(mid)) high = mid;
else low = mid + 1;
}
return low;
function isEnough(minTime) {
// for each bus, Math.floor(minTime / time[i])
let trips = 0;
for (let i = 0; i < time.length; i++) {
trips += Math.floor(minTime / time[i]);
}
return trips >= totalTrips;
}
};
javascript
- Get link
- X
- Other Apps
Comments
Post a Comment