2616. Minimize the Maximum Difference of Pairs #1801
-
Topics: You are given a 0-indexed integer array Note that for a pair of elements at the index Return the minimum maximum difference among all Example 1:
Example 2:
Constraints:
Hint:
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
We need to minimize the maximum difference among Approach
Let's implement this solution in PHP: 2616. Minimize the Maximum Difference of Pairs <?php
/**
* @param Integer[] $nums
* @param Integer $p
* @return Integer
*/
function minimizeMax($nums, $p) {
if ($p == 0) {
return 0;
}
sort($nums);
$n = count($nums);
$low = 0;
$high = $nums[$n - 1] - $nums[0];
while ($low < $high) {
$mid = $low + intval(($high - $low) / 2);
if (canFormPairs($nums, $mid, $p)) {
$high = $mid;
} else {
$low = $mid + 1;
}
}
return $low;
}
/**
* @param $nums
* @param $mid
* @param $p
* @return bool
*/
function canFormPairs($nums, $mid, $p) {
$count = 0;
$i = 0;
$n = count($nums);
while ($i < $n - 1) {
if ($nums[$i + 1] - $nums[$i] <= $mid) {
$count++;
$i += 2;
if ($count >= $p) {
return true;
}
} else {
$i++;
}
}
return $count >= $p;
}
// Test cases
$nums1 = array(10, 1, 2, 7, 1, 3);
$p1 = 2;
echo "Output 1: " . minimizeMax($nums1, $p1) . "\n"; // Output: 1
$nums2 = array(4, 2, 1, 2);
$p2 = 1;
echo "Output 2: " . minimizeMax($nums2, $p2) . "\n"; // Output: 0
?> Explanation:
This approach efficiently narrows down the solution using binary search and validates candidates with a linear pass through the array, ensuring optimal performance. |
Beta Was this translation helpful? Give feedback.
We need to minimize the maximum difference among
p
pairs of indices in an array such that no index appears more than once. The solution involves sorting the array and using binary search to efficiently determine the smallest possible maximum difference.Approach
Problem Analysis: The problem requires selecting
p
pairs of indices from the array such that the maximum absolute difference among all pairs is minimized. Each index can be used at most once. The key insight is that sorting the array allows us to consider adjacent elements for forming pairs with the smallest possible differences, which helps in minimizing the maximum difference.Binary Search Setup: We use binary search on the…