[LeetCode] Count the Number of Fair Pairs

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
1
2
3
4
5
6
7
8
9
10
11
12
13
class Solution {
public:
long long countFairPairs(vector<int>& A, int lower, int upper) {
sort(begin(A), end(A));
long long res = 0;
for(int i = 0; i < A.size(); i++) {
auto lo = lower_bound(begin(A) + i + 1, end(A), lower - A[i]);
auto hi = upper_bound(begin(A) + i + 1, end(A), upper - A[i]);
res += hi - lo;
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2023/02/12/PS/LeetCode/count-the-number-of-fair-pairs/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.