File tree Expand file tree Collapse file tree 1 file changed +41
-0
lines changed Expand file tree Collapse file tree 1 file changed +41
-0
lines changed Original file line number Diff line number Diff line change
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
+ } ;
You can’t perform that action at this time.
0 commit comments