-
Notifications
You must be signed in to change notification settings - Fork 0
/
01-04-2024.java
86 lines (76 loc) · 1.87 KB
/
01-04-2024.java
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
class Node
{
int data;
Node left;
Node right;
Node(int data)
{
this.data = data;
left = null;
right = null;
}
}
class Solution {
public static void mergeSort(ArrayList<Integer> arr, int start, int end) {
if (start >= end) {
return;
}
int mid = (start + end) / 2;
mergeSort(arr, start, mid);
mergeSort(arr, mid + 1, end);
merge(arr, start, mid, end);
}
static int count = 0;
public static void merge(ArrayList<Integer> arr, int start, int mid, int end) {
int i = start;
int j = mid + 1;
ArrayList<Integer> as = new ArrayList<>();
while (i <= mid && j <= end) {
int t = arr.get(i);
int r = arr.get(j);
if (t > r) {
as.add(r);
j++;
int k = mid + 1;
count = count + (k - i);
}
if (t < r) {
as.add(t);
i++;
}
if (t == r) {
as.add(t);
i++;
}
}
while (i <= mid) {
as.add(arr.get(i));
i++;
}
while (j <= end) {
as.add(arr.get(j));
j++;
}
for (int k = 0; k < as.size(); k++) {
arr.set(start, as.get(k));
start++;
}
}
public static void rec(Node root, ArrayList<Integer> arr) {
if (root == null) {
return;
}
rec(root.left, arr);
arr.add(root.data);
rec(root.right, arr);
}
public static int pairsViolatingBST(int n, Node root) {
ArrayList<Integer> arr = new ArrayList<>();
rec(root, arr);
mergeSort(arr, 0, arr.size() - 1);
int tn = 0;
tn = count;
count = 0;
return tn;
}
}