Each split must occur between two 1s, and the number of ways to split is the product of the number of ways to split between each pair of 1s. For each gap of zeros between two 1s, we can split after any of the zeros, so the number of ways is (gap length + 1).
classSolution {
public:int numberOfGoodSubarraySplits(vector<int>& nums) {
constint MOD =1e9+7;
vector<int> pos;
for (int i =0; i < nums.size(); ++i) if (nums[i] ==1) pos.push_back(i);
if (pos.empty()) return0;
longlong ans =1;
for (int i =1; i < pos.size(); ++i) ans = ans * (pos[i] - pos[i-1]) % MOD;
return ans;
}
};
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
funcnumberOfGoodSubarraySplits(nums []int) int {
constmod = 1_000_000_007pos:= []int{}
fori, v:=rangenums {
ifv==1 {
pos = append(pos, i)
}
}
if len(pos) ==0 {
return0 }
ans:=1fori:=1; i < len(pos); i++ {
ans = ans* (pos[i] -pos[i-1]) %mod }
returnans}
1
2
3
4
5
6
7
8
9
10
11
12
import java.util.*;
classSolution {
publicintnumberOfGoodSubarraySplits(int[] nums) {
int mod = 1_000_000_007;
List<Integer> pos =new ArrayList<>();
for (int i = 0; i < nums.length; i++) if (nums[i]== 1) pos.add(i);
if (pos.isEmpty()) return 0;
long ans = 1;
for (int i = 1; i < pos.size(); i++) ans = ans * (pos.get(i) - pos.get(i-1)) % mod;
return (int)ans;
}
}
1
2
3
4
5
6
7
8
9
10
11
classSolution {
funnumberOfGoodSubarraySplits(nums: IntArray): Int {
val mod = 1_000_000_007
val pos = mutableListOf<Int>()
for (i in nums.indices) if (nums[i] ==1) pos.add(i)
if (pos.isEmpty()) return0var ans = 1Lfor (i in1 until pos.size) ans = ans * (pos[i] - pos[i-1]) % mod
return ans.toInt()
}
}
1
2
3
4
5
6
7
8
9
10
11
from typing import List
classSolution:
defnumberOfGoodSubarraySplits(self, nums: List[int]) -> int:
MOD =10**9+7 pos = [i for i, v in enumerate(nums) if v ==1]
ifnot pos:
return0 ans =1for i in range(1, len(pos)):
ans = ans * (pos[i] - pos[i-1]) % MOD
return ans
1
2
3
4
5
6
7
8
9
10
11
12
impl Solution {
pubfnnumber_of_good_subarray_splits(nums: Vec<i32>) -> i32 {
let m =1_000_000_007;
let pos: Vec<_>= nums.iter().enumerate().filter(|&(_, &v)| v ==1).map(|(i, _)| i).collect();
if pos.is_empty() { return0; }
letmut ans =1i64;
for i in1..pos.len() {
ans = ans * (pos[i] - pos[i-1]) asi64% m;
}
ans asi32 }
}
1
2
3
4
5
6
7
8
9
10
11
classSolution {
numberOfGoodSubarraySplits(nums: number[]):number {
constmod=1_000_000_007;
constpos: number[] = [];
for (leti=0; i<nums.length; i++) if (nums[i] ===1) pos.push(i);
if (pos.length===0) return0;
letans=1;
for (leti=1; i<pos.length; i++) ans=ans* (pos[i] -pos[i-1]) %mod;
returnans;
}
}