Minimize the Maximum Difference of Pairs
To solve this problem, let’s first understand the key insight:
If we sort the array nums
, then to minimize the maximum difference among p
pairs, we should try pairing the numbers as closely as possible in the sorted array.
To determine if a difference diff
is achievable or not, we can iterate through the sorted array. For each number, we can try pairing it with the nearest number that is within diff
distance.
Given this insight, we can employ a binary search on the diff
to find the smallest possible value of diff
for which p
pairs can be formed. The search space for diff
ranges from 0
to nums[-1] - nums[0]
.
Here’s the approach:
- Sort the array and keep the original indices using
enumerate
. - Define a function
canFormPairs
that checks ifp
pairs can be formed for a givendiff
. - Use binary search to find the smallest
diff
for whichcanFormPairs
returnsTrue
.
Here’s the code:
|
|
This solution has a time complexity of O(n log n)
due to sorting and binary search.