forked from AnasImloul/Leetcode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCount Number of Teams.java
35 lines (33 loc) · 965 Bytes
/
Count Number of Teams.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
// Smaller * Larger Solution
// sum of #smaller * #larger
// Time complexity: O(N^2)
// Space complexity: O(1)
class Solution {
public int numTeams(int[] rating) {
final int N = rating.length;
int res = 0;
for (int i = 1; i < N; i++) {
res += smaller(rating, i, -1) * larger(rating, i, 1);
res += larger(rating, i, -1) * smaller(rating, i, 1);
}
return res;
}
private int smaller(int[] rating, int i, int diff) {
int t = rating[i], count = 0;
i += diff;
while (i >= 0 && i < rating.length) {
if (rating[i] < t) count++;
i += diff;
}
return count;
}
private int larger(int[] rating, int i, int diff) {
int t = rating[i], count = 0;
i += diff;
while (i >= 0 && i < rating.length) {
if (rating[i] > t) count++;
i += diff;
}
return count;
}
}