-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathInversionCountInArray.java
More file actions
114 lines (72 loc) · 1.92 KB
/
InversionCountInArray.java
File metadata and controls
114 lines (72 loc) · 1.92 KB
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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
/*
Inversion count in an array
Problem Description
Given an array of integers A. If i < j and A[i] > A[j] then the pair (i, j) is called an inversion of A. Find the total number of inversions of A modulo (109 + 7).
Problem Constraints
1 <= length of the array <= 100000
1 <= A[i] <= 10^9
Input Format
The only argument given is the integer array A.
Output Format
Return the number of inversions of A modulo (109 + 7).
Example Input
Input 1:
A = [3, 2, 1]
Input 2:
A = [1, 2, 3]
Example Output
Output 1:
3
Output 2:
0
Example Explanation
Explanation 1:
All pairs are inversions.
Explanation 2:
No inversions.
*/
/*
Solution Approach
Algorithm :
Traverse through the array from start to end
For every element find the count of elements smaller than the current number upto that index using another loop.
Sum up the count of inversion for every index.
Print the count of inversions.
*/
public class Solution {
int count = 0;
int mod = 1000000007;
public int solve(int[] A) {
mergeSort(A, 0, A.length-1);
// System.out.println(Arrays.toString(A));
return count;
}
public void mergeSort(int[] A, int start, int end){
if(start>=end){
return;
}
int mid = start + (end-start)/2;
mergeSort(A, start, mid);
mergeSort(A, mid+1, end);
merge(A, start, mid, end);
}
public void merge(int[] A, int start, int mid, int end){
int[] left = new int[mid-start+1];
for(int i=start; i<=mid;i++){
left[i-start] = A[i];
}
int i=0, k=start;
for(int j=mid+1;i<left.length&&j<=end;){
if(left[i]<=A[j]){
A[k++] = left[i++];
}
else{
count = (count+(left.length-i))%mod;
A[k++] = A[j++];
}
}
while(i<left.length){
A[k++] = left[i++];
}
}
}