1248. Count Number of Nice Subarrays

https://leetcode.com/problems/count-number-of-nice-subarrays/

Given an array of integers nums and an integer k. A continuous subarray is called nice if there are k odd numbers on it.

Return the number of nice sub-arrays.

public int numberOfSubarrays(int[] nums, int k) {
        return subarray(nums, k) - subarray(nums, k-1);
    }
    
    public int subarray(int[] nums, int k) {
        int res = 0;
        int left = 0;
        int count = 0;
        for(int right = 0; right < nums.length; right++) {
            k -= nums[right] % 2;
            while (k < 0) {
                k += nums[left] % 2;
                left++;
            }
            res += right - left + 1;
        }
        return res;
    }

 

posted @ 2020-09-26 07:29  胖虎刷题  阅读(66)  评论(0)    收藏  举报