Find p pairs of numbers in the array nums that minimize the sum of the absolute values of the differences.
Ideas:
The minimum difference should be generated between a pair of numbers with similar values, so that the numbers with similar values are as close together as possible to facilitate calculation, so sorting is required.
Here we do not directly consider a pair of numbers, but directly consider the value of the difference.
Use binary search to search for a difference.
The left boundary is 0, and the right boundary is the maximum value - minimum value in nums (the rightmost number after nums sorting - the leftmost number).
Determine mid = difference, then if the absolute value of the difference between a pair of numbers <= this difference, it means that it is satisfied,
traverse the array nums, calculate how many pairs of numbers satisfy <= the difference, record it as cnt pair,
if cnt > = p, indicating that the number pairs with the difference within mid can reach p, which can further reduce the difference, right= mid.
Otherwise, left = mid+1.
class Solution {
int n = 0;
public int minimizeMax(int[] nums, int p) {
n = nums.length;
Arrays.sort(nums);
int left = 0;
int right = nums[n-1] - nums[0];
while(left < right) {
int mid = left + (right - left) / 2;
if(canMakePairs(mid, nums, p)) {
right = mid;
} else {
left = mid + 1;
}
}
return left;
}
boolean canMakePairs(int mid, int[] nums, int p) {
int cnt = 0;
for(int i = 0; i < n-1 && cnt < p;i++){
//在这里限制cnt<p,因为p可以是0
if(nums[i+1] - nums[i] <= mid) {
cnt ++;
i ++; //加上for里面的i++,相当于i向右移动2位
}
}
return cnt >= p;
}
}