Premium Only Content

2563. Count the Number of Fair Pairs
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:
0 <= i < j < n, and
lower <= nums[i] + nums[j] <= upper
Example 1:
Input: nums = [0,1,7,4,4,5], lower = 3, upper = 6
Output: 6
Explanation: There are 6 fair pairs: (0,3), (0,4), (0,5), (1,3), (1,4), and (1,5).
Example 2:
Input: nums = [1,7,9,2,5], lower = 11, upper = 11
Output: 1
Explanation: There is a single fair pair: (2,3).
Constraints:
1 <= nums.length <= 105
nums.length == n
-109 <= nums[i] <= 109
-109 <= lower <= upper <= 109
class Solution {
public:
long long countFairPairs(vector<int>& nums, int lower, int upper) {
ranges::sort(nums);
return countLess(nums, upper) - countLess(nums, lower - 1);
}
private:
long countLess(const vector<int>& nums, int sum) {
long res = 0;
for (int i = 0, j = nums.size() - 1; i < j; ++i) {
while (i < j && nums[i] + nums[j] > sum)
--j;
res += j - i;
}
return res;
}
};
-
LIVE
Game On!
19 hours ago $0.96 earnedHappy FOOTBALL FRIDAY! Week 3 NFL Betting Preview!
1,158 watching -
15:10
Michael Button
15 hours ago $2.35 earnedGroundbreaking Discovery at Giza Pyramids?
44.3K8 -
18:11
Tactical Considerations
15 hours ago $1.71 earnedIs This the Best Truck Gun for 2025?
11.9K3 -
8:37
The Art of Improvement
20 hours ago $0.71 earnedLife Lessons I’d Tell My Teenage Self
10.5K3 -
LIVE
BEK TV
23 hours agoTrent Loos in the Morning - 9/19/2025
193 watching -
17:22
Adam Does Movies
13 hours ago $1.80 earnedIce Road: Vengeance - Movie Review
67K4 -
45:05
Uncommon Sense In Current Times
17 hours ago $1.00 earnedDarwin vs. DNA | Dr. Nathaniel Jeanson on Creation Science, Evolution & the Case for Genesis
18.6K3 -
32:19
The Lou Holtz Show
14 hours agoThe Lou Holtz Show S2 EP18 | Danica Patrick on Fearlessness, Faith & Finding Purpose #podcast
17.2K4 -
23:41
The Official Corbett Report Rumble Channel
11 hours agoDiscord Democracy is Coming For Us All! - New World Next Week
17.9K15 -
49:14
CharLee Simons presents DO NOT TALK
1 day agoSCREW YOU, ZUCKERBERG (Sam Anthony is back!)
19.2K1