2616. Minimize the Maximum Difference of Pairs (binary search idea
T: O(nlogn)
S: O(1)```java
class Solution {
public int minimizeMax(int[] nums, int p) {
Arrays.sort(nums);
int left = 0;
int right = nums[nums.length-1] - nums[0];
while (left < right) {
int mid = left + (right - left)/2;
//System.out.println("mid:" + mid);
int pairCount = 0;
for (int i = 0; i < nums.length-1; i++) {
if (nums[i+1] - nums[i] <= mid) {
pairCount++;
i++; // jump to next pair index (choose this i and i+1 pair)
}
}
if (pairCount >= p) {
right = mid;
} else {
left = mid+1;
}
}
return left;
}
}
/*
T: O(nlogn)
S: O(1)
0 1 2 3 4 5
[10,1,2,7,1,3]
find pair
then return maximum diff
find all pair -> O(n^2)
cal diff and sort asc -> nlogn
find max diff of pair -> O(p)
anyway it doesn't work.
how to reduce find all pair?
or how to find small diff quickly?
sort?
[10,1,2,7,1,3]
1,1,2,3,7,10
0~9
left = 0
right = 9
0 4 9
-------------------
0 3
1 right
mid = 0 + 9/2 = 4
p = [1,1], [2,3], [7,10]
right = mid - 1 = 4 - 1 = 3
mid = 0 + 3/2 = 1
p= [1,1], [2,3]
right = mid - 1 = 0
mid = 0
p = [1,1]
pCount < p
left = mid + 1 = 1
---> left > right -> end
return left
so it ok to return left when using left <= right
so...I think I'll use left < right in the future, because it can return left or right, all is ok
*/
```有問題的code
new version
Previous2615. Sum of Distances (same as 2121. Intervals Between Identical Elements)NextTreeMap or TreeSet
Last updated
Was this helpful?