Minimize the Maximum Difference of Pairs Problem
Description
LeetCode Problem 2616.
You are given a 0-indexed integer array nums and an integer p. Find p pairs of indices of nums such that the maximum difference amongst all the pairs is minimized. Also, ensure no index appears more than once amongst the p pairs.
Note that for a pair of elements at the index i and j, the difference of this pair is |nums[i] - nums[j]|, where |x| represents the absolute value of x.
Return the minimum maximum difference among all p pairs. We define the maximum of an empty set to be zero.
Example 1:
Input: nums = [10,1,2,7,1,3], p = 2
Output: 1
Explanation: The first pair is formed from the indices 1 and 4, and the second pair is formed from the indices 2 and 5.
The maximum difference is max(|nums[1] - nums[4]|, |nums[2] - nums[5]|) = max(0, 1) = 1. Therefore, we return 1.
Example 2:
Input: nums = [4,2,1,2], p = 1
Output: 0
Explanation: Let the indices 1 and 3 form a pair. The difference of that pair is |2 - 2| = 0, which is the minimum we can attain.
Constraints:
1 <= nums.length <= 10^50 <= nums[i] <= 10^90 <= p <= (nums.length)/2
Solution
Approach: Binary Search + Greedy
If a maximum difference x is achievable, so is any larger one, so we can binary search on x between 0 and max - min.
To test a value x, sort nums first. In sorted order the best pairs are adjacent elements, so scan left to right: if nums[i + 1] - nums[i] <= x, pair them up, count one pair and skip to i + 2; otherwise move on to i + 1. Pairing greedily as early as possible never hurts. If the count reaches p, x works.
The smallest x that works is the answer (0 when p = 0).
Complexity: O(n log n + n log M) time and O(1) extra space, where n is the length of nums and M is the difference between its largest and smallest values.
class Solution:
def minimizeMax(self, nums: List[int], p: int) -> int:
def check(diff: int) -> bool:
cnt = i = 0
while i < len(nums) - 1:
if nums[i + 1] - nums[i] <= diff:
cnt += 1
i += 2
else:
i += 1
return cnt >= p
nums.sort()
l, r = 0, nums[-1] - nums[0]
while l < r:
mid = (l + r) >> 1
if check(mid):
r = mid
else:
l = mid + 1
return l