Minimize the Maximum Difference of Pairs - 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.
Input & Output
Example 1 — Basic Case
$
Input:
nums = [10,1,2,7,1,3], p = 2
›
Output:
1
💡 Note:
After sorting: [1,1,2,3,7,10]. We can form pairs (1,1) with diff=0 and (2,3) with diff=1. Maximum difference is 1.
Example 2 — Single Pair
$
Input:
nums = [4,2,1,2], p = 1
›
Output:
0
💡 Note:
After sorting: [1,2,2,4]. We can pair (2,2) with difference 0, which is the minimum possible.
Example 3 — Edge Case p=0
$
Input:
nums = [1,2,3,4], p = 0
›
Output:
0
💡 Note:
When p=0, we need to form 0 pairs. The maximum of an empty set is defined as 0.
Constraints
- 1 ≤ nums.length ≤ 105
- 0 ≤ p ≤ (nums.length)/2
- 0 ≤ nums[i] ≤ 109
Visualization
Tap to expand
Understanding the Visualization
1
Input
Array [10,1,2,7,1,3] and p=2 pairs needed
2
Sort & Strategy
Sort array and use binary search on answer
3
Output
Minimum maximum difference is 1
Key Takeaway
🎯 Key Insight: Sort first, then binary search on the maximum difference value with greedy validation
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code