Count Number of Teams LeetCode solution in JavaScript

1
// counting bigger / smaller elements
2
// if after rating[i] has X bigger elements,
3
// and each element has Y bigger elements after them
4
// hence total elements that has i < j < k and rating[i] < rating[j] < rating[k]
5
// same for the number of smaller elements
6
// so the key point here is to know how many elements
7
// that smaller and bigger than the current number
8
var numTeams = function (rating) {
9
// save total number of elements after i
10
// that smaller than rating[i]
11
let big = new Array(rating.length).fill(0);
12

13
let n = rating.length;
14
for (let i = 0; i < n - 1; i++) {
15
for (let j = i + 1; j < n; j++) {
16
if (rating[j] > rating[i]) big[i]++;
17
}
18
}
19

20
let count = 0;
21
for (let i = 0; i < n - 1; i++) {
22
for (let j = i + 1; j < n; j++) {
23
if (rating[j] > rating[i]) count += big[j];
24
// because all elements are unique, so
25
// we don't need to calculate the number of smaller elements
26
// because if there are X bigger elements after rating[i]
27
// then there are (n - i - 1 - X) smaller elements after rating[i]
28
// or small = n - i - 1 - big
29
else count += n - j - 1 - big[j];
30
}
31
}
32

33
return count;
34
};

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0