Problem Description
Given an array of integers and an integer p, form p disjoint pairs (i.e. no index is used more than once) such that the maximum absolute difference among the pairs is minimized. The difference for a pair (i, j) is defined as |nums[i] - nums[j]|. Return the minimized maximum difference.
Key Insights
- Sorting the array clusters numbers with small differences together.
- Use binary search to decide on a candidate maximum difference.
- For each candidate difference during binary search, use a greedy strategy to form pairs:
- Iterate through the sorted array.
- Whenever the difference between consecutive numbers is less than or equal to the candidate, form a pair and skip the next element.
- The goal is to check if at least p pairs can be formed with a candidate difference.
Space and Time Complexity
Time Complexity: O(n log n + n log(max(nums) - min(nums))) Space Complexity: O(n) (for sorting)
Solution
We first sort the array to bring numbers with small differences closer together. Then we use binary search on the possible range of maximum differences. For each candidate value during the binary search, we use a greedy approach to try to form at least p pairs. We iterate through the array and whenever the difference between nums[i] and nums[i+1] is less than or equal to the candidate maximum, we form a pair and move the index forward by two. If we can form p pairs, the candidate value might be too high, and we reduce the range; otherwise we increase it. This balance ensures that we find the smallest candidate maximum difference that allows p pairs.