Skip to content

Commit a854e29

Browse files
authored
Create 2031-count-subarrays-with-more-ones-than-zeros.js
1 parent 85b740c commit a854e29

File tree

1 file changed

+41
-0
lines changed

1 file changed

+41
-0
lines changed
Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
const lowBit = (x) => x & -x
2+
class FenwickTree {
3+
constructor(n) {
4+
if (n < 1) return
5+
this.sum = Array(n + 1).fill(0)
6+
}
7+
update(i, delta) {
8+
if (i < 1) return
9+
while (i < this.sum.length) {
10+
this.sum[i] += delta
11+
i += lowBit(i)
12+
}
13+
}
14+
query(i) {
15+
if (i < 1) return 0
16+
let sum = 0
17+
while (i > 0) {
18+
sum += this.sum[i]
19+
i -= lowBit(i)
20+
}
21+
return sum
22+
}
23+
}
24+
25+
/**
26+
* @param {number[]} nums
27+
* @return {number}
28+
*/
29+
const subarraysWithMoreZerosThanOnes = function(nums) {
30+
const n = nums.length, mod = 1e9 + 7
31+
const bit = new FenwickTree(2 * n + 1)
32+
bit.update(n, 1)
33+
let balance = 0, res = 0
34+
for(const e of nums) {
35+
balance += (e === 1 ? 1 : -1)
36+
bit.update(balance + n, 1)
37+
res = (res + bit.query(balance + n - 1)) % mod
38+
}
39+
40+
return res
41+
};

0 commit comments

Comments
 (0)