-
Notifications
You must be signed in to change notification settings - Fork 12
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Create 2563. Count the Number of Fair Pairs (#634)
- Loading branch information
Showing
1 changed file
with
41 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,41 @@ | ||
class Solution { | ||
public: | ||
// Prateek | ||
long long countFairPairs(vector<int>& arr, int lower, int upper) { | ||
// Declare the answer variable | ||
long long ans=0; | ||
int n=arr.size(); | ||
sort(arr.begin(),arr.end()); | ||
//sort the array so that we can apply binary search | ||
// for every i we have to findits lower and upper | ||
// since (a,b),(b,a) will be counted as 1 only | ||
// we can apply binary seach from i+1 | ||
for(int i=0;i<n;i++){ | ||
// left and right are the left and right indexes for every i | ||
int l=i+1,r=n-1,left=-1,right=-1; | ||
while(l<=r){ | ||
int mid=(l+r)/2; | ||
if(arr[i]+arr[mid]>=lower){ | ||
left=mid; | ||
r=mid-1; | ||
} | ||
else | ||
l=mid+1; | ||
} | ||
l=i+1,r=n-1; | ||
while(l<=r){ | ||
int mid=(l+r)/2; | ||
if(arr[i]+arr[mid]<=upper){ | ||
right=mid; | ||
l=mid+1; | ||
} | ||
else | ||
r=mid-1; | ||
} | ||
if(left!=-1&&right!=-1){ | ||
ans+=(right-left+1);} | ||
|
||
} | ||
return ans; | ||
} | ||
}; |