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

Beautiful Towers II - Monotonic Increasing Stack [JS]

Check if There is a Valid Partition For The Array - Two Approaches - DP & Recursion w/ Memoization [JS]

Minimum Number of Operations to Sort a Binary Tree by Level - BFS & Cycle Counting Explained [JS]

Count Elements With Maximum Frequency - Hashmap [JS]

Mice and Cheese - Greedy w/ Sorting [JS]