Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
Skip to content

Commit 5df4e7b

Browse files
committed
Add solution #2616
1 parent 087a594 commit 5df4e7b

File tree

2 files changed

+54
-0
lines changed

2 files changed

+54
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1943,6 +1943,7 @@
19431943
2609|[Find the Longest Balanced Substring of a Binary String](./solutions/2609-find-the-longest-balanced-substring-of-a-binary-string.js)|Easy|
19441944
2610|[Convert an Array Into a 2D Array With Conditions](./solutions/2610-convert-an-array-into-a-2d-array-with-conditions.js)|Medium|
19451945
2615|[Sum of Distances](./solutions/2615-sum-of-distances.js)|Medium|
1946+
2616|[Minimize the Maximum Difference of Pairs](./solutions/2616-minimize-the-maximum-difference-of-pairs.js)|Medium|
19461947
2618|[Check if Object Instance of Class](./solutions/2618-check-if-object-instance-of-class.js)|Medium|
19471948
2619|[Array Prototype Last](./solutions/2619-array-prototype-last.js)|Easy|
19481949
2620|[Counter](./solutions/2620-counter.js)|Easy|
Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
/**
2+
* 2616. Minimize the Maximum Difference of Pairs
3+
* https://leetcode.com/problems/minimize-the-maximum-difference-of-pairs/
4+
* Difficulty: Medium
5+
*
6+
* You are given a 0-indexed integer array nums and an integer p. Find p pairs of indices
7+
* of nums such that the maximum difference amongst all the pairs is minimized. Also, ensure
8+
* no index appears more than once amongst the p pairs.
9+
*
10+
* Note that for a pair of elements at the index i and j, the difference of this pair is
11+
* |nums[i] - nums[j]|, where |x| represents the absolute value of x.
12+
*
13+
* Return the minimum maximum difference among all p pairs. We define the maximum of an empty
14+
* set to be zero.
15+
*/
16+
17+
/**
18+
* @param {number[]} nums
19+
* @param {number} p
20+
* @return {number}
21+
*/
22+
var minimizeMax = function(nums, p) {
23+
nums.sort((a, b) => a - b);
24+
const n = nums.length;
25+
26+
let left = 0;
27+
let right = nums[n - 1] - nums[0];
28+
let result = 0;
29+
30+
while (left <= right) {
31+
const mid = Math.floor((left + right) / 2);
32+
if (canFormPairs(mid)) {
33+
result = mid;
34+
right = mid - 1;
35+
} else {
36+
left = mid + 1;
37+
}
38+
}
39+
40+
return result;
41+
42+
function canFormPairs(maxDiff) {
43+
let pairs = 0;
44+
for (let i = 0; i < n - 1 && pairs < p; i += 2) {
45+
if (nums[i + 1] - nums[i] <= maxDiff) {
46+
pairs++;
47+
} else {
48+
i--;
49+
}
50+
}
51+
return pairs >= p;
52+
}
53+
};

0 commit comments

Comments
 (0)