1487. Closest Pairs Budget
A dance teacher must choose exactly p pairs of students from a group whose heights are listed in nums. No student can appear in two pairs. Within a pair the height difference is |nums[i] - nums[j]|, and the teacher wants the largest difference among the p chosen pairs to be as small as possible.
Return that minimum possible largest difference; when p = 0 no pair is needed and the answer is 0. Sort the heights and binary search a limit X: scan the sorted list and pair two neighbours whenever their gap is at most X (then skip both), otherwise move on by one; the limit works if at least p pairs result. Expected time is O(n log n) with O(n) extra space.
Example 1
- Input:
- nums = [10,1,13,4,2,11], p = 2
- Output:
- 1
- Explanation:
Sorted values are 1, 2, 4, 10, 11, 13; pairing (1,2) and (10,11) keeps every gap at most 1.
Example 2
- Input:
- nums = [5,5,9], p = 0
- Output:
- 0
- Explanation:
No pair has to be chosen, so the largest gap is 0.
Example 3
- Input:
- nums = [0,1000000000], p = 1
- Output:
- 1000000000
- Explanation:
The only possible pair has a difference of one billion.
Constraints
1 ≤ n ≤ 105
0 ≤ nums[i] ≤ 109
0 ≤ p ≤ n / 2
How this problem is judged
- Answers
- Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
- Time per case
- Python 4,000 msC++ 1,000 msJava 2,000 msJavaScript 2,000 msTypeScript 2,000 ms
Expected complexity
- Time
- O(n log n)
- Space
- O(n)