-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCount Pairs in an Array
54 lines (54 loc) Β· 1.23 KB
/
Count Pairs in an Array
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
49
50
51
52
53
54
class Solution{
public:
int merge(vector<int>& arr,int l,int r,int m){
int n1=m-l+1;
int n2=r-m;
int left[n1];
int right[n2];
for(int i=0;i<n1;i++){
left[i]=arr[l+i];
}
for(int i=0;i<n2;i++){
right[i]=arr[m+i+1];
}
int i=0,j=0,ans=0,k=l;
while(i<n1 && j<n2){
if(left[i]<=right[j]){
arr[k]=left[i];
i++,k++;
}
else{
arr[k]=right[j];
j++,k++;
ans+=(n1-i);
}
}
while(i<n1){
arr[k]=left[i];
k++,i++;
}
while(j<n2){
arr[k]=right[j];
k++,j++;
}
return ans;
}
long long int mergesort(vector<int>& arr,int l,int r){
long long int c=0;
if(l<r){
int m=(r+l)/2;
c+=mergesort(arr,l,m);
c+=mergesort(arr,m+1,r);
c+=merge(arr,l,r,m);
}
return c;
}
int countPairs(int arr[] , int n )
{
vector<int>arr2(n);
for(int i=0;i<n;i++){
arr2[i]=arr[i]*i;
}
return (int)mergesort(arr2,0,n-1);
}
};