You are given a binary array nums containing only the integers 0 and 1.
Return _the number ofsubarrays in nums that have more _1’s than0
_’ s. Since the answer may be very large, return it modulo _109 + 7.
A subarray is a contiguous sequence of elements within an array.
Input: nums =[0,1,1,0,1]Output: 9Explanation:
The subarrays of size 1 that have more ones than zeros are:[1],[1],[1]The subarrays of size 2 that have more ones than zeros are:[1,1]The subarrays of size 3 that have more ones than zeros are:[0,1,1],[1,1,0],[1,0,1]The subarrays of size 4 that have more ones than zeros are:[1,1,0,1]The subarrays of size 5 that have more ones than zeros are:[0,1,1,0,1]
Example 2:
1
2
3
4
Input: nums =[0]Output: 0Explanation:
No subarrays have more ones than zeros.
Example 3:
1
2
3
4
Input: nums =[1]Output: 1Explanation:
The subarrays of size 1 that have more ones than zeros are:[1]
We can map 1 to +1 and 0 to -1, and use prefix sums to track the difference between ones and zeros. For each prefix sum, we want to count how many previous prefix sums are less than the current, which can be done efficiently with a Binary Indexed Tree (Fenwick Tree) after coordinate compression.
classSolution {
publicintcountSubarrays(int[] nums) {
int n = nums.length, MOD = 1_000_000_7;
int[] psum =newint[n+1];
for (int i = 0; i < n; i++) psum[i+1]= psum[i]+ (nums[i]== 1 ? 1 : -1);
int[] sorted = psum.clone();
Arrays.sort(sorted);
Map<Integer, Integer> idx =new HashMap<>();
int id = 0;
for (int x : sorted) if (!idx.containsKey(x)) idx.put(x, id++);
FenwickTree bit =new FenwickTree(id);
int ans = 0;
for (int x : psum) {
int i = idx.get(x);
ans = (ans + bit.query(i-1)) % MOD;
bit.update(i, 1);
}
return ans;
}
classFenwickTree {
int[] tree;
FenwickTree(int n) { tree =newint[n+2]; }
voidupdate(int i, int v) { for (i++; i < tree.length; i += i &-i) tree[i]+= v; }
intquery(int i) {
int res = 0;
for (i++; i > 0; i -= i &-i) res += tree[i];
return res;
}
}
}
classSolution:
defcountSubarrays(self, nums: list[int]) -> int:
MOD =10**9+7 n = len(nums)
psum = [0]
for x in nums:
psum.append(psum[-1] + (1if x ==1else-1))
sorted_psum = sorted(set(psum))
idx = {v: i for i, v in enumerate(sorted_psum)}
classBIT:
def__init__(self, n):
self.t = [0]*(n+2)
defupdate(self, i, v):
i +=1while i < len(self.t):
self.t[i] += v
i += i &-i
defquery(self, i):
i +=1 res =0while i >0:
res += self.t[i]
i -= i &-i
return res
bit = BIT(len(idx))
ans =0for x in psum:
i = idx[x]
ans = (ans + bit.query(i-1)) % MOD
bit.update(i, 1)
return ans