Problem
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.
Examples
Example 1:
| |
Example 2:
| |
Solution
Method 1 - Binary Search
We start by sorting the array to focus on the differences between elements rather than their original order.
The possible answer lies between left = 0 and right = nums[n-1] - nums[0].
Using binary search, for each mid = (left + right) / 2, we check if it’s possible to form p pairs where the difference in each pair is at most mid.
We greedily pair adjacent elements if their difference is less than or equal to mid, skipping to the next available pair each time a pair is formed.
After each check, if we can form at least p pairs, we set right = mid; otherwise, we set left = mid + 1.
The final answer is the value of left after binary search completes.
Code
| |
| |
Complexity
- Time:
O(n log D),nis length ofnumsandDis difference between max and min innums. Sorting takes O(n log n), and each binary search step (O(log D)) does an O(n) greedy check. - Space:
O(1)