6359. 最小化数对的最大差值
【二分 + 贪心】二分 [0, 1e9] 的解空间,然后贪心验证,验证时将数组从小到大排序,如果前一个和后一个的间隔 <= 当前验证的 x,那么个数 + 1,同时跳过下一个元素,最后看能欧组成 p 个。
class Solution {
// 二分 + 贪心验证
int[] nums;
int n, p;
boolean check(int x) {
int t = 0, i = 0;
while (i < n - 1) {
if (nums[i + 1] - nums[i] <= x) {
t++;
i += 2;
} else {
i++;
}
}
return t >= p;
}
public int minimizeMax(int[] nums, int p) {
int l = 0, r = (int)1e9;
Arrays.sort(nums);
this.nums = nums;
this.n = nums.length;
this.p = p;
while (l <= r) {
int m = (l + r) >> 1;
if (!check(m)) l = m + 1;
else r = m - 1;
}
return l;
}
}