Count Number of Nice Subarrays LeetCode solution in Java

1
class Solution {
2
public int numberOfSubarrays(int[] nums, int k) {
3
int i = 0;
4
int j = 0;
5
int odd = 0;
6
int result = 0;
7
int temp = 0;
8

9
/*
10
Approach : two pointer + sliding window technique
11

12
step 1 : we have fix i and moving j until our count of odd numbers == k
13
step 2 : when(odd == count) we are counting every possible subarray by reducing the size of subarray from i
14

15
why temp?
16
from reducing the size of subarray we will count all the possible subarray from between i and j
17
but when i encounter a odd element the odd count will reduce and that while will stop executing
18

19
now there are two possible cases
20
1.The leftover elements have a odd number
21
2.The leftover elements do not have any odd number
22

23
1. if our leftover elements have a odd number
24
then we cannot include our old possible subarrays into new possible subarrays because now new window for having odd == k is formed
25
that's why temp = 0;
26

27
2. if out leftover elements do not have any odd element left
28
then our leftover elements must also take in consideration becuase they will also contribute in forming subarrays
29
*/
30
while (j < nums.length) {
31
if (nums[j] % 2 != 0) {
32
odd++;
33
// if leftover elements have odd element then new window is formed so we set temp = 0;
34
temp = 0;
35
}
36
while (odd == k) {
37
temp++;
38
if (nums[i] % 2 != 0) odd--;
39
i++;
40
}
41
// if no leftover elements is odd, each element will part in forming subarray
42
// so include them
43
result += temp;
44
j++;
45
}
46
return result;
47
}
48
}

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0