Skip to content

Latest commit

 

History

History

2750

Folders and files

NameName
Last commit message
Last commit date

parent directory

..
 
 

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

Related Topics:
Array, Math, Dynamic Programming

Similar Questions:

Hints:

  • If the array consists of only 0s answer is 0.
  • In the final split, exactly one separation point exists between two consecutive 1s.
  • In how many ways can separation points be put?

Solution 1.

// OJ: https://leetcode.com/problems/ways-to-split-array-into-good-subarrays
// Author: github.com/lzl124631x
// Time: O(N)
// Space: O(1)
class Solution {
public:
    int numberOfGoodSubarraySplits(vector<int>& A) {
        long ans = 1, mod = 1e9 + 7, N = A.size(), zero = 0, seenOne = 0;
        for (int i = 0; i < N; ++i) {
            if (A[i] == 1) {
                if (seenOne) ans = ans * (zero + 1) % mod;
                seenOne = 1;
                zero = 0;
            } else zero++;
        }
        return seenOne ? ans : 0;
    }
};