-
Notifications
You must be signed in to change notification settings - Fork 0
/
PairSum.cpp
48 lines (43 loc) · 1.26 KB
/
PairSum.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
#include <bits/stdc++.h>
using namespace std;
int getPairsCount(int a[], int n, int k) {
sort(a,a+n);
int i=0,j=n-1,c=0;
while(i<j)
{
int s=a[i]+a[j];
if(s<k)i++; //if sum is less, we take a larger element for sum
else if(s>k) j--; //if sum is greater, we take a smaller element for sum
else
{
// Find the frequency of a[i]
int x=a[i],xx=i;
while(i<j && a[i]==x)
i++;
// Find the frequency of a[j]
int y = a[j], yy = j;
while (j >= i and a[j] == y)
j--;
// If a[i] and a[j] are same
// then remove the extra number counted
if (x == y) {
int temp = i - xx + yy - j - 1;
c += (temp * (temp + 1)) / 2;
}
else
c += (i - xx) * (yy - j);
}
}
return c;
}
int main()
{
int n,k;
cin>>n>>k;
int a[n];
for(int i=0;i<n;i++)
cin>>a[i];
int ans=getPairsCount(a,n,k);
cout<<ans<<endl;
return 0;
}