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

Beautiful Towers II - Monotonic Increasing Stack [JS]

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

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

Maximum Score After Applying Operations on a Tree - DFS [JS]

Divide Nodes Into the Maximum Number of Groups - Union Find & BFS [JS]