Skip to content

Commit fed48a7

Browse files
committed
leetcode
1 parent 19e23dc commit fed48a7

File tree

3 files changed

+97
-0
lines changed

3 files changed

+97
-0
lines changed
Lines changed: 66 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,66 @@
1+
/*
2+
3+
-* 2616. Minimize the Maximum Difference of Pairs *-
4+
5+
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.
6+
7+
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.
8+
9+
Return the minimum maximum difference among all p pairs. We define the maximum of an empty set to be zero.
10+
11+
12+
13+
Example 1:
14+
15+
Input: nums = [10,1,2,7,1,3], p = 2
16+
Output: 1
17+
Explanation: The first pair is formed from the indices 1 and 4, and the second pair is formed from the indices 2 and 5.
18+
The maximum difference is max(|nums[1] - nums[4]|, |nums[2] - nums[5]|) = max(0, 1) = 1. Therefore, we return 1.
19+
Example 2:
20+
21+
Input: nums = [4,2,1,2], p = 1
22+
Output: 0
23+
Explanation: Let the indices 1 and 3 form a pair. The difference of that pair is |2 - 2| = 0, which is the minimum we can attain.
24+
25+
26+
Constraints:
27+
28+
1 <= nums.length <= 105
29+
0 <= nums[i] <= 109
30+
0 <= p <= (nums.length)/2
31+
32+
*/
33+
34+
class Solution {
35+
int minimizeMax(List<int> nums, int p) {
36+
nums.sort();
37+
int left = 0;
38+
int right = nums[nums.length - 1] - nums[0];
39+
40+
while (left < right) {
41+
int mid =left + (right + left) ~/ 2;
42+
if (helper(nums, mid, p)) {
43+
right = mid;
44+
} else {
45+
left = mid + 1;
46+
}
47+
}
48+
49+
return left;
50+
}
51+
52+
bool helper(List<int> nums, int mid, int p) {
53+
int count = 0;
54+
for (int i = 0; i < nums.length - 1 && count < p;) {
55+
if (nums[i + 1] - nums[i] <= mid) {
56+
count++;
57+
i += 2;
58+
} else {
59+
i++;
60+
}
61+
}
62+
return count >= p;
63+
}
64+
}
65+
66+
Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
package main
2+
3+
import "sort"
4+
5+
func solve(nums []int, mid int) int {
6+
pairs := 0
7+
for j := 0; j+1 < len(nums); j++ {
8+
if nums[j+1]-nums[j] <= mid {
9+
pairs++
10+
j++
11+
}
12+
}
13+
return pairs
14+
}
15+
16+
func minimizeMax(nums []int, p int) int {
17+
sort.Ints(nums)
18+
sols := 0
19+
low, high := 0, nums[len(nums)-1]
20+
for low <= high {
21+
mid := (high + low) / 2
22+
pairs := solve(nums, mid)
23+
if pairs >= p {
24+
sols = mid
25+
high = mid - 1
26+
} else {
27+
low = mid + 1
28+
}
29+
}
30+
return sols
31+
}

MinimizeTheMaximumDifferenceOfPairs/minimize_the_maximum_difference_of_pairs.md

Whitespace-only changes.

0 commit comments

Comments
 (0)