[LeetCode] Ways to Split Array Into Good Subarrays

2750. Ways to Split Array Into Good Subarrays

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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22

class Solution {
public:
int numberOfGoodSubarraySplits(vector<int>& nums) {
vector<int> cnt;
for(int i = 0, now = 0, ok = false; i < nums.size(); i++) {
if(nums[i] == 0) now += 1;
if(nums[i] == 1) {
if(ok) cnt.push_back(now);
now = 0;
}
if(nums[i] == 1) ok = true;
if(i == nums.size() - 1 and !ok) return 0;
}
long long res = 1, mod = 1e9 + 7;
for(int i = 0; i < cnt.size(); i++) {
res = res * (cnt[i] + 1) % mod;
}
return res;
}
};

Author: Song Hayoung
Link: https://songhayoung.github.io/2023/06/25/PS/LeetCode/ways-to-split-array-into-good-subarrays/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.