Dashboard Temp Share Shortlinks Frames API

HTMLify

count-subarray-with-k-odds.py
Views: 1 | Author: prakhardoneria
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
class Solution:
    def countSubarrays(self, arr, k):
        def countAtMost(limit):
            if limit < 0:
                return 0
            res = 0
            left = 0
            odd_count = 0
            for right in range(len(arr)):
                if arr[right] % 2 != 0:
                    odd_count += 1
                while odd_count > limit:
                    if arr[left] % 2 != 0:
                        odd_count -= 1
                    left += 1
                res += (right - left + 1)
            return res
        
        return countAtMost(k) - countAtMost(k - 1)