Skip to content

Commit 9fb75ce

Browse files
committed
Add Count Nice Subarrays sliding window algorithm
1 parent fe6066b commit 9fb75ce

File tree

2 files changed

+68
-0
lines changed

2 files changed

+68
-0
lines changed
Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
package com.thealgorithms.slidingwindow;
2+
3+
public class CountNiceSubarrays {
4+
private CountNiceSubarrays() {
5+
}
6+
7+
public static int countNiceSubarrays(int[] nums, int k) {
8+
int n = nums.length;
9+
int left = 0;
10+
int oddCount = 0;
11+
int result = 0;
12+
int[] memo = new int[n];
13+
14+
for (int right = 0; right < n; right++) {
15+
if ((nums[right] & 1) == 1) {
16+
oddCount++;
17+
}
18+
19+
if (oddCount > k) {
20+
left += memo[left];
21+
oddCount--;
22+
}
23+
24+
if (oddCount == k) {
25+
if (memo[left] == 0) {
26+
int count = 0;
27+
int temp = left;
28+
while ((nums[temp] & 1) == 0) {
29+
count++;
30+
temp++;
31+
}
32+
memo[left] = count + 1;
33+
}
34+
result += memo[left];
35+
}
36+
}
37+
return result;
38+
}
39+
}
Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
package com.thealgorithms.slidingwindow;
2+
import static org.junit.jupiter.api.Assertions.assertEquals;
3+
import org.junit.jupiter.api.Test;
4+
5+
public class CountNiceSubarraysTest {
6+
@Test
7+
void testExampleCase() {
8+
int[] nums = {1, 1, 2, 1, 1};
9+
assertEquals(2, CountNiceSubarrays.countNiceSubarrays(nums, 3));
10+
}
11+
12+
@Test
13+
void testAllEvenNumbers() {
14+
int[] nums = {2, 4, 6, 8};
15+
assertEquals(0, CountNiceSubarrays.countNiceSubarrays(nums, 1));
16+
}
17+
18+
@Test
19+
void testSingleOdd() {
20+
int[] nums = {1};
21+
assertEquals(1, CountNiceSubarrays.countNiceSubarrays(nums, 1));
22+
}
23+
24+
@Test
25+
void testMultipleChoices() {
26+
int[] nums = {2, 2, 1, 2, 2, 1, 2};
27+
assertEquals(9, CountNiceSubarrays.countNiceSubarrays(nums, 2));
28+
}
29+
}

0 commit comments

Comments
 (0)