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
๐Ÿ•บ Dance Partner Problem ๐Ÿ’ƒDancers by Skill Level (Sorted):1123710๐ŸŽฏ Goal: Form 2 pairs, minimize max skill gapBinary Search Range: 0 to 9โœ… Optimal Pairing (Max Gap = 1):1123Gap: 0Gap: 1๐Ÿ’ก Key InsightGreedy pairing of adjacent dancers gives optimal results!
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!
Asked in
Google 45 Meta 38 Amazon 32 Microsoft 28
67.0K Views
Medium Frequency
~25 min Avg. Time
1.8K 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