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
```java
ๅพ้กๆ, ๆ่ฆบๅพ, ้ฃๆๅฐฑ sort, ็ถๅพ็ฎๅบๅๅ diff
ๅจ sort diff, ๅๅ p ๅ, ไธๅฐฑๆฏ็ญๆกๅ ไฝ้ๆจฃๆฏๆๅ้ก็
[3,4,2,3,2,1,2]
why this can't, because it reuse the "index"
1 2 2 2 3 3 4
1 0 0 1 0 1
้ธไบ index 0 ็ 0
ไธๅ 2 2 ๅฐฑไธ่ฝๅ็จไบ
2 2 2
0 0. -> ๅช่ฝ้ธๅ
ถไธญไธๅ0
ๆไปฅ้ๆจฃsort diff ๆๅๅนพๅ, ๆฏๆ้่ค็จๅฐ index ็ ->ไธๅฏ่ก
ๆฌ้ก้้ตๅจๆผ, sort ๅพ, ้ธไบๆๅฐ(้ฐๅฑ
)ๆๅฐฑๅฏไปฅ่ทณๅฐไธๅไบ greedy ็ๆณๆณ,
ๅ ็บๅฆๆไปๅคฉๆไธๆ้ฐๅฑ
, ไธฆไธ่ฝ็ข็่ผๅฐ็ diff, ๅ ็บ sort ๅพ็้ฐๅฑ
, ๆ่ฝๅพๅฐๅฐ diff
class Solution {
public int minimizeMax(int[] nums, int p) {
Arrays.sort(nums);
List<Integer> diff = new ArrayList<>();
for (int i = 0; i < nums.length-1;i++) {
diff.add(Math.abs(nums[i] - nums[i+1]));
}
Collections.sort(diff);
int result = 0;
for (int i = 0; i < p; i++) {
result = Math.max(result, diff.get(i));
}
return result;
}
}
/*
[10,1,2,7,1,3], p = 2
```
```
new version
```java
class Solution {
public int minimizeMax(int[] nums, int p) {
Arrays.sort(nums);
int left = 0;
int right = nums[nums.length-1] - nums[0];
int result = Integer.MAX_VALUE;
while (left <= right) {
int mid = left + (right - left)/2;
int pCount = 0;
for (int i = 0; i < nums.length-1; i++) {
if (nums[i+1] - nums[i] <= mid) {
pCount++;
i++;
}
}
if (pCount >= p) {
result = Math.min(result, mid);
right = mid - 1;
} else {
left = mid + 1;
}
}
return result;
}
}
/*
[10,1,2,7,1,3], p = 2
[3,4,2,3,2,1,2]
why this can't, because it reuse the "index"
1 2 2 2 3 3 4
1 0 0 1 0 1
้ธไบ index 0 ็ 0
ไธๅ 2 2 ๅฐฑไธ่ฝๅ็จไบ
2 2 2
0 0. -> ๅช่ฝ้ธๅ
ถไธญไธๅ0
ๆไปฅ้ๆจฃsort diff ๆๅๅนพๅ, ๆฏๆ้่ค็จๅฐ index ็ ไธๅฏ่ก
1 1 2 3 7 10
0 1 1 4 3
*/
```
Previous2615. Sum of Distances (same as 2121. Intervals Between Identical Elements)NextTreeMap or TreeSet
Last updated