2563. Count the Number of Fair Pairs
Difficulty: Medium
Topics: Array, Two Pointers, Binary Search, Sorting
Given a 0-indexed integer array nums of size n and two integers lower and upper, return the number of fair pairs.
A pair (i, j) is fair if:
Example 1:
Example 2:
Constraints:
Hint:
Solution:
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) { ... ... ... /** * go to ./solution.php */ } /** * Helper function for binary search to find left boundary * * @param $arr * @param $target * @param $start * @return int|mixed */ function lowerBound($arr, $target, $start) { ... ... ... /** * go to ./solution.php */ } /** * Helper function for binary search to find right boundary * * @param $arr * @param $target * @param $start * @return int|mixed */ function upperBound($arr, $target, $start) { ... ... ... /** * go to ./solution.php */ } // Example usage: $nums = [0, 1, 7, 4, 4, 5]; $lower = 3; $upper = 6; echo countFairPairs($nums, $lower, $upper); // Output: 6 ?>
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.
Contact Links
If you found this series helpful, please consider giving the repository a star on GitHub or sharing the post on your favorite social networks ?. Your support would mean a lot to me!
If you want more helpful content like this, feel free to follow me:
The above is the detailed content of Count the Number of Fair Pairs. For more information, please follow other related articles on the PHP Chinese website!