1248. Count Number of Nice Subarrays

Link

Solution

  public int numberOfSubarrays(int[] nums, int k) {
        int ret = 0;
        int start = 0, end = 0, count = 0;
        
        while(end < nums.length){
            if(nums[end]%2 != 0){
                k--;
            }
            if(k == 0) count = 0; //set the possible start count = 0
            while(k == 0){
                count++; //current start is possilbe start, increase count
                
                //unpower the effect of current start to see next one start pointer
                if(nums[start] % 2 != 0){
                    k++;
                }
                start++; //increase start and recheck again
            }
            end++;
            ret += count;
        }
        return ret;
    }

Last updated

Was this helpful?