-
Notifications
You must be signed in to change notification settings - Fork 3
/
_1395_CountNumberOfTeams.java
61 lines (48 loc) · 1.28 KB
/
_1395_CountNumberOfTeams.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
package io.github.tahanima.leetcode;
/**
* @author tahanima
*/
public class _1395_CountNumberOfTeams {
int MAXN = 100005;
int[] BIT = new int[MAXN];
public void update(int x, int delta) {
for(; x < MAXN; x += x&-x) {
BIT[x] += delta;
}
}
public int query(int x) {
int sum = 0;
for(; x > 0; x -= x&-x) {
sum += BIT[x];
}
return sum;
}
public int numTeams(int[] rating) {
int n = rating.length;
int[] greater = new int[n];
int[] less = new int[n];
for (int i = n - 1; i >= 0; i--) {
greater[i] = query(MAXN - 1) - query(rating[i]);
update(rating[i], 1);
}
for (int i = 0; i < MAXN; i++) {
BIT[i] = 0;
}
for (int i = n - 1; i >= 0; i--) {
less[i] = query(rating[i] - 1);
update(rating[i], 1);
}
int answer = 0;
for (int i = 0; i < n; i++) {
for (int j = i + 1; j < n; j++) {
if (rating[i] < rating[j]) {
answer += greater[j];
}
if (rating[i] > rating[j]) {
answer += less[j];
}
}
}
return answer;
}
}