All Downloads are FREE. Search and download functionalities are using the official Maven repository.

g1201_1300.s1248_count_number_of_nice_subarrays.Solution.kt Maven / Gradle / Ivy

There is a newer version: 1.32
Show newest version
package g1201_1300.s1248_count_number_of_nice_subarrays

// #Medium #Array #Hash_Table #Math #Sliding_Window
// #2023_06_09_Time_431_ms_(93.33%)_Space_48.7_MB_(80.00%)

class Solution {
    fun numberOfSubarrays(nums: IntArray, k: Int): Int {
        var oddLen = 0
        var startIndex = 0
        var num = 0
        var endIndex: Int
        var res = 0
        var hasK: Boolean
        for (i in nums.indices) {
            hasK = false
            endIndex = i
            if (nums[i] % 2 == 1) {
                oddLen++
            }
            while (oddLen >= k) {
                hasK = true
                if (nums[startIndex++] % 2 == 1) {
                    oddLen--
                }
                num++
            }
            res += num
            while (hasK && ++endIndex < nums.size && nums[endIndex] % 2 == 0) {
                res += num
            }
            num = 0
        }
        return res
    }
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy