Skip to content

Commit b87194f

Browse files
authored
Create 1395-count-number-of-teams.js
1 parent f761ca0 commit b87194f

File tree

1 file changed

+64
-0
lines changed

1 file changed

+64
-0
lines changed

1395-count-number-of-teams.js

Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,64 @@
1+
/**
2+
* @param {number[]} rating
3+
* @return {number}
4+
*/
5+
const numTeams = function(rating) {
6+
let res = 0
7+
for(let i = 1, n = rating.length; i < n - 1; i++) {
8+
const less = Array(2).fill(0), greater = Array(2).fill(0)
9+
for(let j = 0; j < n; j++) {
10+
if(rating[i] > rating[j]) {
11+
less[j < i ? 0 : 1]++
12+
}
13+
if(rating[i] < rating[j]) {
14+
greater[j > i ? 0 : 1]++
15+
}
16+
}
17+
res += less[0] * greater[0] + less[1] * greater[1]
18+
}
19+
return res
20+
};
21+
22+
23+
// another
24+
25+
/**
26+
* @param {number[]} rating
27+
* @return {number}
28+
*/
29+
const numTeams = function(rating) {
30+
if(rating.length < 3) return 0
31+
const n = rating.length
32+
const leftTree = Array(1e5 + 1).fill(0)
33+
const rightTree = Array(1e5 + 1).fill(0)
34+
for(let r of rating) update(rightTree, r, 1)
35+
let res = 0
36+
for(let r of rating) {
37+
update(rightTree, r, -1)
38+
res += getPrefixSum(leftTree, r - 1) * getSuffixSum(rightTree, r + 1)
39+
res += getSuffixSum(leftTree, r + 1) * getPrefixSum(rightTree, r - 1)
40+
update(leftTree, r, 1)
41+
}
42+
43+
return res
44+
};
45+
46+
function update(bit, index, val) {
47+
while(index < bit.length) {
48+
bit[index] += val
49+
index += index & (-index)
50+
}
51+
}
52+
53+
function getPrefixSum(bit, index) {
54+
let res = 0
55+
while(index > 0) {
56+
res += bit[index]
57+
index -= index & (-index)
58+
}
59+
return res
60+
}
61+
62+
function getSuffixSum(bit, index) {
63+
return getPrefixSum(bit, 1e5) - getPrefixSum(bit, index - 1)
64+
}

0 commit comments

Comments
 (0)