#2616
Minimize the Maximum Difference of Pairs
MediumArrayBinary SearchDynamic ProgrammingGreedySortingBinary SearchGreedy
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n log n) |
| Space | O(1) | O(1) |
💡
Intuition
Time O(n log n)Space O(1)
By sorting the array first, we can efficiently pair the closest elements together, minimizing the maximum difference. We can then use binary search to find the smallest maximum difference that allows forming p pairs.
⚙️
Algorithm
4 steps- 1Step 1: Sort the array.
- 2Step 2: Use binary search on the possible maximum differences (from 0 to max(nums) - min(nums)).
- 3Step 3: For each mid value in the binary search, check if it's possible to form p pairs without exceeding this difference.
- 4Step 4: Adjust the binary search bounds based on whether forming p pairs was successful.
solution.py23 lines
1# Full working Python code
2def canFormPairs(nums, p, maxDiff):
3 count = 0
4 i = 0
5 while i < len(nums) - 1:
6 if nums[i + 1] - nums[i] <= maxDiff:
7 count += 1
8 i += 2 # skip the next element as it's paired
9 else:
10 i += 1
11 return count >= p
12
13
14def minimizeMax(nums, p):
15 nums.sort()
16 left, right = 0, nums[-1] - nums[0]
17 while left < right:
18 mid = (left + right) // 2
19 if canFormPairs(nums, p, mid):
20 right = mid # try for a smaller max difference
21 else:
22 left = mid + 1 # increase max difference
23 return leftℹ
Complexity note: Sorting the array takes O(n log n), and checking pairs takes O(n), making this approach efficient overall.
- 1Sorting the array helps in minimizing differences.
- 2Binary search allows efficient exploration of possible maximum differences.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.