|
| 1 | +/* |
| 2 | +
|
| 3 | +-* 2616. Minimize the Maximum Difference of Pairs *- |
| 4 | +
|
| 5 | +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. |
| 6 | +
|
| 7 | +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. |
| 8 | +
|
| 9 | +Return the minimum maximum difference among all p pairs. We define the maximum of an empty set to be zero. |
| 10 | +
|
| 11 | + |
| 12 | +
|
| 13 | +Example 1: |
| 14 | +
|
| 15 | +Input: nums = [10,1,2,7,1,3], p = 2 |
| 16 | +Output: 1 |
| 17 | +Explanation: The first pair is formed from the indices 1 and 4, and the second pair is formed from the indices 2 and 5. |
| 18 | +The maximum difference is max(|nums[1] - nums[4]|, |nums[2] - nums[5]|) = max(0, 1) = 1. Therefore, we return 1. |
| 19 | +Example 2: |
| 20 | +
|
| 21 | +Input: nums = [4,2,1,2], p = 1 |
| 22 | +Output: 0 |
| 23 | +Explanation: Let the indices 1 and 3 form a pair. The difference of that pair is |2 - 2| = 0, which is the minimum we can attain. |
| 24 | + |
| 25 | +
|
| 26 | +Constraints: |
| 27 | +
|
| 28 | +1 <= nums.length <= 105 |
| 29 | +0 <= nums[i] <= 109 |
| 30 | +0 <= p <= (nums.length)/2 |
| 31 | +
|
| 32 | +*/ |
| 33 | + |
| 34 | +class Solution { |
| 35 | + int minimizeMax(List<int> nums, int p) { |
| 36 | + nums.sort(); |
| 37 | + int left = 0; |
| 38 | + int right = nums[nums.length - 1] - nums[0]; |
| 39 | + |
| 40 | + while (left < right) { |
| 41 | + int mid =left + (right + left) ~/ 2; |
| 42 | + if (helper(nums, mid, p)) { |
| 43 | + right = mid; |
| 44 | + } else { |
| 45 | + left = mid + 1; |
| 46 | + } |
| 47 | + } |
| 48 | + |
| 49 | + return left; |
| 50 | + } |
| 51 | + |
| 52 | + bool helper(List<int> nums, int mid, int p) { |
| 53 | + int count = 0; |
| 54 | + for (int i = 0; i < nums.length - 1 && count < p;) { |
| 55 | + if (nums[i + 1] - nums[i] <= mid) { |
| 56 | + count++; |
| 57 | + i += 2; |
| 58 | + } else { |
| 59 | + i++; |
| 60 | + } |
| 61 | + } |
| 62 | + return count >= p; |
| 63 | + } |
| 64 | +} |
| 65 | + |
| 66 | + |
0 commit comments