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 Pairs INPUT Original Array nums: 10 1 2 7 1 3 i=0 i=1 i=2 i=3 i=4 i=5 p = 2 (pairs needed) After Sorting: 1 1 2 3 7 10 Adjacent Differences: 0 1 1 4 3 Goal: Find 2 pairs with minimum max difference GREEDY ALGORITHM 1 Sort Array Sorted: [1,1,2,3,7,10] 2 Binary Search Search range: [0, 9] mid = max allowed diff 3 Greedy Check For mid=1, count pairs with diff <= mid Checking mid = 1: 1 1 2 3 7 10 Pair1: (1,1) diff=0 OK Pair2: (2,3) diff=1 OK 4 Found 2 pairs! 2 >= p, so mid=1 works Try smaller mid next FINAL RESULT Optimal Pairs Found: Pair 1: (1, 1) Difference = |1-1| = 0 Pair 2: (2, 3) Difference = |2-3| = 1 Maximum of differences: max(0, 1) = 1 OUTPUT 1 OK - Minimum possible max difference is 1 Key Insight: 1. Sort array first - adjacent elements have minimum differences after sorting. 2. Use binary search on the answer (max diff) and greedy validation to count pairs. 3. Greedy: scan left to right, pair adjacent elements if diff <= mid, then skip both. TutorialsPoint - Minimize the Maximum Difference of Pairs | Greedy + Binary Search Approach
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