Skip to content

Commit 985bb99

Browse files
authored
Create 2563. Count the Number of Fair Pairs (#634)
2 parents c555d0e + 41e04be commit 985bb99

File tree

1 file changed

+41
-0
lines changed

1 file changed

+41
-0
lines changed

2563. Count the Number of Fair Pairs

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
class Solution {
2+
public:
3+
// Prateek
4+
long long countFairPairs(vector<int>& arr, int lower, int upper) {
5+
// Declare the answer variable
6+
long long ans=0;
7+
int n=arr.size();
8+
sort(arr.begin(),arr.end());
9+
//sort the array so that we can apply binary search
10+
// for every i we have to findits lower and upper
11+
// since (a,b),(b,a) will be counted as 1 only
12+
// we can apply binary seach from i+1
13+
for(int i=0;i<n;i++){
14+
// left and right are the left and right indexes for every i
15+
int l=i+1,r=n-1,left=-1,right=-1;
16+
while(l<=r){
17+
int mid=(l+r)/2;
18+
if(arr[i]+arr[mid]>=lower){
19+
left=mid;
20+
r=mid-1;
21+
}
22+
else
23+
l=mid+1;
24+
}
25+
l=i+1,r=n-1;
26+
while(l<=r){
27+
int mid=(l+r)/2;
28+
if(arr[i]+arr[mid]<=upper){
29+
right=mid;
30+
l=mid+1;
31+
}
32+
else
33+
r=mid-1;
34+
}
35+
if(left!=-1&&right!=-1){
36+
ans+=(right-left+1);}
37+
38+
}
39+
return ans;
40+
}
41+
};

0 commit comments

Comments
 (0)