Minimize the Maximum Difference of Pairs - Binary Search [JS]
Solution: Binary Search
- 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.
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
Post a Comment