[LeetCode] Minimize the Maximum Difference of Pairs

2616. Minimize the Maximum Difference of Pairs

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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
class Solution {
bool helper(vector<int>& A, int d, int p) {
for(int i = A.size() - 1; i > 0 and p > 0; i--) {
if(A[i] - A[i-1] <= d) {
p -= 1;
i -= 1;
}
}
return p <= 0;
}
public:
int minimizeMax(vector<int>& A, int p) {
sort(begin(A), end(A));
int l = 0, r = A.back() - A.front(), res = r;
while(l <= r) {
int m = l + (r - l) / 2;
bool ok = helper(A,m,p);
if(ok) {
r = m - 1;
res = min(res, m);
} else l = m + 1;
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2023/04/09/PS/LeetCode/minimize-the-maximum-difference-of-pairs/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.