44 * Counts the number of "nice subarrays".
55 * A nice subarray is a contiguous subarray that contains exactly k odd numbers.
66 *
7- * This implementation uses the sliding window technique.
7+ * Approach:
8+ * This implementation uses a sliding window technique.
9+ * The window expands using a right pointer and shrinks from the left when the
10+ * number of odd elements exceeds k. Even numbers do not affect the odd count
11+ * and can be freely included in the window.
12+ *
13+ * Example:
14+ * Input: nums = [1, 1, 2, 1, 1], k = 3
15+ * Output: 2
16+ *
17+ * Explanation:
18+ * The subarrays with exactly 3 odd numbers are:
19+ * [1, 1, 2, 1]
20+ * [1, 2, 1, 1]
821 *
922 * Reference:
1023 * https://leetcode.com/problems/count-number-of-nice-subarrays/
@@ -35,44 +48,30 @@ public static int countNiceSubarrays(int[] nums, int k) {
3548 // Tracks number of odd elements in the current window
3649 int oddCount = 0 ;
3750
38- // Final answer: total number of nice subarrays
51+ // Stores the total number of nice subarrays
3952 int result = 0 ;
4053
41- /*
42- * memo[i] stores how many valid starting positions exist
43- * when the left pointer is at index i.
44- *
45- * This avoids recomputing the same values again.
46- */
54+ // memo[i] stores how many valid subarrays can start at index i
4755 int [] memo = new int [n ];
4856
49- // Right pointer moves forward to expand the window
57+ // Right pointer expands the window
5058 for (int right = 0 ; right < n ; right ++) {
5159
52- // If current element is odd, increment odd count
60+ // Increment odd count if current number is odd
5361 if ((nums [right ] & 1 ) == 1 ) {
5462 oddCount ++;
5563 }
5664
57- /*
58- * If oddCount exceeds k, shrink the window from the left
59- * until oddCount becomes valid again.
60- */
65+ // Shrink the window if odd count exceeds k
6166 if (oddCount > k ) {
6267 left += memo [left ];
6368 oddCount --;
6469 }
6570
66- /*
67- * When the window contains exactly k odd numbers,
68- * count all possible valid subarrays starting at `left`.
69- */
71+ // When exactly k odd numbers are present
7072 if (oddCount == k ) {
7173
72- /*
73- * If this left index hasn't been processed before,
74- * count how many consecutive even numbers follow it.
75- */
74+ // Calculate number of valid subarrays starting at left (only once)
7675 if (memo [left ] == 0 ) {
7776 int count = 0 ;
7877 int temp = left ;
@@ -83,14 +82,11 @@ public static int countNiceSubarrays(int[] nums, int k) {
8382 temp ++;
8483 }
8584
86- /*
87- * Number of valid subarrays starting at `left`
88- * is (count of even numbers + 1)
89- */
85+ // Valid subarrays = consecutive evens + 1
9086 memo [left ] = count + 1 ;
9187 }
9288
93- // Add number of valid subarrays for this left position
89+ // Add valid subarrays count for current window
9490 result += memo [left ];
9591 }
9692 }
0 commit comments