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
Minimize Maximum Difference of PairsInput: nums = [10,1,2,7,1,3], p = 21012713SortAfter sorting: [1,1,2,3,7,10]1123710Pair 1: |1-1|=0Pair 2: |2-3|=1Output: Minimum Maximum Difference = 1Formed 2 pairs with maximum difference = max(0,1) = 1
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
Asked in
Google 15 Amazon 12 Microsoft 8
28.5K Views
Medium Frequency
~25 min Avg. Time
847 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen