Minimize the Maximum Difference of Pairs - Problem
Imagine you're a matchmaker trying to create the most harmonious pairs possible! ๐ฏ
You have an array of integers nums and need to form exactly p pairs from these numbers. Your goal is to minimize the maximum difference among all pairs you create.
The Challenge: Each number can only be used once, and you want to make sure that even the "worst" pair (the one with the largest difference) is as good as possible.
For example, if nums = [10, 1, 2, 7, 1, 3] and p = 2, you could pair:
- Option 1: (1,1) and (2,3) โ differences: 0 and 1 โ maximum = 1
- Option 2: (1,2) and (3,7) โ differences: 1 and 4 โ maximum = 4
Clearly, Option 1 is better! Return the minimum possible maximum difference.
Note: If p = 0 (no pairs needed), return 0.
Input & Output
example_1.py โ Basic Case
$
Input:
nums = [10,1,2,7,1,3], p = 2
โบ
Output:
1
๐ก Note:
The optimal pairing is (1,1) with difference 0 and (2,3) with difference 1. The maximum difference is 1, which is the minimum possible.
example_2.py โ Single Pair
$
Input:
nums = [4,2,1,2], p = 1
โบ
Output:
0
๐ก Note:
We can pair the two 2's together, giving us a difference of 0, which is optimal.
example_3.py โ No Pairs Needed
$
Input:
nums = [1,2,3,4], p = 0
โบ
Output:
0
๐ก Note:
No pairs are needed, so we return 0 by definition.
Constraints
- 1 โค nums.length โค 105
- 0 โค nums[i] โค 109
- 0 โค p โค (nums.length)/2
- Each index can appear in at most one pair
Visualization
Tap to expand
Understanding the Visualization
1
Line Up Dancers
Sort dancers by skill level so similar dancers are adjacent
2
Binary Search Strategy
Ask: 'Can we form enough pairs with max skill gap โค X?'
3
Greedy Pairing
Always pair adjacent dancers when possible - they have the smallest gaps
4
Find Sweet Spot
Binary search finds the minimum X where we can form enough pairs
Key Takeaway
๐ฏ Key Insight: Binary search on the answer + greedy validation creates an elegant O(n log n) solution that's both intuitive and optimal!
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code