Minimize the Maximum Difference of Pairs - Binary Search [JS]

Description 

Solution: Binary Search

First sort nums in asc order.
Then, binary search for the minimum maximum difference.
To check if we can make p pairs with maximum difference of x,

  • Greedily try to take adjacent pairs.
  • Logic: Taking adjacent pairs ensures that the difference will be minimized. If we don't take adjacent pairs, the gaps left over will be larger than if we took adjacent pairs.

Time Complexity: O(n log(n)) 124ms
Space Complexity: O(log(n)) (space for sorting) 54.6MB

var minimizeMax = function(nums, p) {
  if (p === 0) return 0;
  nums.sort((a, b) => a - b);
  let n = nums.length, low = 0, high = nums[n - 1] - nums[0];
  while (low < high) {
    let mid = Math.floor((low + high) / 2);
    if (isEnough(mid)) high = mid;
    else low = mid + 1;
  }
  return low;
  
  function isEnough(maxDiff) {
    let i = 1, pairs = 0;
    while (i < n) {
      if (nums[i] - nums[i - 1] <= maxDiff) {
        pairs++;
        i += 2;
      } else {
        i++;
      }
      if (pairs === p) return true;
    }
    return false;
  }
};

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]