Description
You are given a binary array nums containing only the integers 0 and 1. Return the number of subarrays in nums that have more 1's than 0's. Since the answer may be very large, return it modulo 109 + 7.
A subarray is a contiguous sequence of elements within an array.
Example 1:
Input: nums = [0,1,1,0,1] Output: 9 Explanation: 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:
Input: nums = [0] Output: 0 Explanation: No subarrays have more ones than zeros.
Example 3:
Input: nums = [1] Output: 1 Explanation: The subarrays of size 1 that have more ones than zeros are: [1]
Constraints:
1 <= nums.length <= 1050 <= nums[i] <= 1
Solutions
Solution 1: Prefix Sum + Binary Indexed Tree
The problem requires us to count the number of subarrays where the count of 1 is greater than the count of 0. If we treat 0 in the array as -1, then the problem becomes counting the number of subarrays where the sum of elements is greater than 0.
To calculate the sum of elements in a subarray, we can use the prefix sum. To count the number of subarrays where the sum of elements is greater than 0, we can use a binary indexed tree to maintain the occurrence count of each prefix sum. Initially, the occurrence count of the prefix sum 0 is 1.
Next, we traverse the array nums, use variable s to record the current prefix sum, and use variable ans to record the answer. For each position i, we update the prefix sum s, then query the occurrence count of the prefix sum in the range [0, s) in the binary indexed tree, add it to ans, and then update the occurrence count of s in the binary indexed tree.
Finally, return ans.
The time complexity is O(n × log n), and the space complexity is O(n). Where n is the length of the array nums.
class BinaryIndexedTree: __slots__ = ["n", "c"] def __init__(self, n: int): self.n = n self.c = [0] * (n + 1) def update(self, x: int, v: int): while x <= self.n: self.c[x] += v x += x & -x def query(self, x: int) -> int: s = 0 while x: s += self.c[x] x -= x & -x return s class Solution: def subarraysWithMoreZerosThanOnes(self, nums: List[int]) -> int: n = len(nums) base = n + 1 tree = BinaryIndexedTree(n + base) tree.update(base, 1) mod = 10**9 + 7 ans = s = 0 for x in nums: s += x or -1 ans += tree.query(s - 1 + base) ans %= mod tree.update(s + base, 1) return ans(code-box)
Solution 2
class Solution: def subarraysWithMoreZerosThanOnes(self, nums: List[int]) -> int: sl = SortedList([0]) mod = 10**9 + 7 ans = s = 0 for x in nums: s += x or -1 ans += sl.bisect_left(s) ans %= mod sl.add(s) return ans(code-box)
