Minimum Time to Complete Trips - Binary Search

Description

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

Comments

Popular posts from this blog

Maximum Value of an Ordered Triplet II - Two Solutions [JS]

Maximum Sum of Distinct Subarrays With Length K - Sliding Window w/ Two Pointers & Set [JS]

Sum of Prefix Scores of Strings - Trie [JS]

Maximum Count of Positive Integer and Negative Integer - Binary Search [JS]

Count Subarrays With Median K - Count Left & Right Balance [JS]