Description
You are given a binary array nums
.
A subarray of an array is good if it contains exactly one element with the value 1
.
Return an integer denoting the number of ways to split the array nums
into good subarrays. As the number may be too large, return it modulo 109 + 7
.
A subarray is a contiguous non-empty sequence of elements within an array.
Β
Example 1:
Input: nums = [0,1,0,0,1] Output: 3 Explanation: There are 3 ways to split nums into good subarrays: - [0,1] [0,0,1] - [0,1,0] [0,1] - [0,1,0,0] [1]
Example 2:
Input: nums = [0,1,0] Output: 1 Explanation: There is 1 way to split nums into good subarrays: - [0,1,0]
Β
Constraints:
1 <= nums.length <= 105
0 <= nums[i] <= 1
Solution
Python3
class Solution:
def numberOfGoodSubarraySplits(self, nums: List[int]) -> int:
N = len(nums)
res = 0
M = 10 ** 9 + 7
ones = []
for i, x in enumerate(nums):
if x == 1:
ones.append(i)
if len(ones) == 0: return 0
res = 1
for i in range(1, len(ones)):
diff = ones[i] - ones[i - 1]
res *= diff
res %= M
return res