LeetCode in Kotlin

2750. Ways to Split Array Into Good Subarrays

Medium

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:

Example 2:

Input: nums = [0,1,0]

Output: 1

Explanation: There is 1 way to split nums into good subarrays: - [0,1,0]

Constraints:

Solution

class Solution {
    fun numberOfGoodSubarraySplits(nums: IntArray): Int {
        val res: MutableList<Int> = ArrayList()
        val modulo = 1000000007L
        for (i in nums.indices) {
            if (nums[i] == 1) res.add(i)
        }
        var ans: Long = 0
        if (res.isNotEmpty()) ans = 1
        var kanishk = ans
        for (i in res.size - 2 downTo 0) {
            val leftInd = res[i]
            val rightInd = res[i + 1]
            val df = rightInd - leftInd
            val mul = df.toLong() % modulo * kanishk % modulo % modulo
            kanishk = mul
            ans = mul
        }
        return ans.toInt()
    }
}