1248. Count Number of Nice Subarrays

T: O(n)
S: O(1)
```java
/*
[2,2,2,1,2,2,1,2,2,2,1]
         c c c 
*/
class Solution {
    public int numberOfSubarrays(int[] nums, int k) {
        int result = 0;
        int count = 0;
        int right = 0;
        int left = 0;
        int n = nums.length;
        while (right < n) {
            int current = nums[right];
            right++;
            if (current % 2 == 1) {
                k--;
                count = 0;
            }
            while (k == 0) {
                if (nums[left] % 2 == 1) {
                    k++;
                }
                left++;
                count++;
            }
            result += count;
        }
        return result;
    }
}

/*
using sliding win
T: O(n)
S: O(1)

[1,1,2,1,1]
       x 
         x

      4 subarray
[2,2,2,1,2,2,1,2,2,2]
             r
       k++
         l     then in the later, if it still even, means we have more count*( even number count)
       4       4 4 4 
             satis -> shrink left   

  so           4 + 4 + 4 + 4 = 16      

[2,2,2,1,2,2,1,2,2,2,1]. if in the later, there's odd, re-cal count, so in this range we have new count = 3  =>  (2 2 1 2 2 2 1) & (2 1 2 2 2 1)  & (1 2 2 2 1)
         c c c

when odd = k
 shrink left
 left++ 
  count++

*/
```

latest sliding win

class Solution {
    public int numberOfSubarrays(int[] nums, int k) {
        int n = nums.length;
        int result = 0;
        int count = 0;
        int left = 0;

        for (int right = 0; right < n; right++) {
            int rightNum = nums[right];
            if (rightNum % 2 == 1) {
                k--;
                count = 0; // this is the key
            }
            while (left < n && k == 0) {
                if (nums[left] % 2 == 1) {
                    k++;
                }
                left++;
                count++; // 1, 1
            }
            result += count;
        }
        return result;
    }
}

/**
1 1 2 1 1
      x
  l     r 


ex3: all these 16 results

2,2,2,[1,2,2,1],2,2,2
0 0 0 1. 1 1 2  2 2 2
-> 16 = 4 + 4 + 4 + 4
[2,2,2,1,2,2,1],
[2,2,1,2,2,1],
[2,1,2,2,1],
[1,2,2,1] 

[2,2,2,1,2,2,1,2],
[2,2,1,2,2,1,2],
[2,1,2,2,1,2],
[1,2,2,1,2]

[2,2,2,1,2,2,1,2,2],
[2,2,1,2,2,1,2,2],
[2,1,2,2,1,2,2],
[1,2,2,1,2,2]

[2,2,2,1,2,2,1,2,2,2],
[2,2,1,2,2,1,2,2,2],
[2,1,2,2,1,2,2,2],
[1,2,2,1,2,2,2]
 */

Last updated