2563. Count the Number of Fair Pairs #826
Answered
by
mah-shamim
mah-shamim
asked this question in
Q&A
-
Topics: Given a 0-indexed integer array A pair (i, j) is fair if:
Example 1:
Example 2:
Constraints:
Hint:
|
Beta Was this translation helpful? Give feedback.
Answered by
mah-shamim
Nov 13, 2024
Replies: 1 comment 2 replies
-
We can use the following approach:
Let's implement this solution in PHP: 2563. Count the Number of Fair Pairs <?php
/**
* @param Integer[] $nums
* @param Integer $lower
* @param Integer $upper
* @return Integer
*/
function countFairPairs($nums, $lower, $upper) {
sort($nums);
$n = count($nums);
$count = 0;
for ($i = 0; $i < $n - 1; $i++) {
$low = $lower - $nums[$i];
$high = $upper - $nums[$i];
$left = $this->lowerBound($nums, $low, $i + 1);
$right = $this->upperBound($nums, $high, $i + 1);
$count += $right - $left;
}
return $count;
}
/**
* Helper function for binary search to find left boundary
*
* @param $arr
* @param $target
* @param $start
* @return int|mixed
*/
function lowerBound($arr, $target, $start) {
$left = $start;
$right = count($arr);
while ($left < $right) {
$mid = intval(($left + $right) / 2);
if ($arr[$mid] < $target) {
$left = $mid + 1;
} else {
$right = $mid;
}
}
return $left;
}
/**
* Helper function for binary search to find right boundary
*
* @param $arr
* @param $target
* @param $start
* @return int|mixed
*/
function upperBound($arr, $target, $start) {
$left = $start;
$right = count($arr);
while ($left < $right) {
$mid = intval(($left + $right) / 2);
if ($arr[$mid] <= $target) {
$left = $mid + 1;
} else {
$right = $mid;
}
}
return $left;
}
// Example usage:
$nums = [0, 1, 7, 4, 4, 5];
$lower = 3;
$upper = 6;
echo countFairPairs($nums, $lower, $upper); // Output: 6
?> Explanation:
This approach has a time complexity of O(n log n) due to sorting and binary search for each element, which is efficient enough for large inputs. |
Beta Was this translation helpful? Give feedback.
2 replies
Answer selected by
topugit
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
We can use the following approach:
nums[i]
, find the range[lower, upper] - nums[i]
forj > i
. We use binary search to find the smallest and largest indices that satisfy this range.Let's implement this solution in PHP: 2563. Count the Number of Fair Pairs