-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathreversepair.java
More file actions
63 lines (56 loc) · 1.74 KB
/
Copy pathreversepair.java
File metadata and controls
63 lines (56 loc) · 1.74 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
import java.util.ArrayList;
public class reversepair {
private static void merge(int[] arr, int low, int mid, int high) {
ArrayList<Integer> temp = new ArrayList<>();
int left = low;
int right = mid + 1;
while (left <= mid && right <= high) {
if (arr[left] <= arr[right]) {
temp.add(arr[left]);
left++;
} else {
temp.add(arr[right]);
right++;
}
}
while (left <= mid) {
temp.add(arr[left]);
left++;
}
while (right <= high) {
temp.add(arr[right]);
right++;
}
for (int i = low; i <= high; i++) {
arr[i] = temp.get(i - low);
}
}
public static int countPairs(int[] arr, int low, int mid, int high) {
int right = mid + 1;
int cnt = 0;
for (int i = low; i <= mid; i++) {
while (right <= high && arr[i] > (2*(long)arr[right])) right++;
cnt += (right - (mid + 1));
}
return cnt;
}
public static int mergeSort(int[] arr, int low, int high) {
int cnt = 0;
if (low >= high) return cnt;
int mid = (low + high) / 2 ;
cnt += mergeSort(arr, low, mid);
cnt += mergeSort(arr, mid + 1, high);
cnt += countPairs(arr, low, mid, high);
merge(arr, low, mid, high);
return cnt;
}
public static int reversePairs(int[] arr) {
return mergeSort(arr, 0, arr.length - 1);
}
public static void main(String[] args) {
int[] arr = {1, 3, 2, 3, 1};
System.out.println(reversePairs(arr));
}
}
// time complexity -O(nlogn)
// space complexity - O(n)