forked from ex01tus/leetcode-grind
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCountNumberOfNiceSubarrays.java
More file actions
60 lines (48 loc) · 1.46 KB
/
CountNumberOfNiceSubarrays.java
File metadata and controls
60 lines (48 loc) · 1.46 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
package array;
import java.util.HashMap;
import java.util.Map;
/**
* Description: https://leetcode.com/problems/count-number-of-nice-subarrays
* Difficulty: Medium
*/
public class CountNumberOfNiceSubarrays {
/**
* Time complexity: O(n)
* Space complexity: O(n)
*/
public int numberOfSubarraysViaPrefixSum(int[] nums, int k) {
Map<Integer, Integer> prefixSum = new HashMap<>();
int count = 0;
int currentSum = 0;
for (int num : nums) {
currentSum += (num % 2 == 0) ? 0 : 1;
int currentSubarray = currentSum == k ? 1 : 0;
int prevSubarray = prefixSum.getOrDefault(currentSum - k, 0);
count += currentSubarray + prevSubarray;
prefixSum.merge(currentSum, 1, Integer::sum);
}
return count;
}
/**
* Time complexity: O(n)
* Space complexity: O(1)
*/
public int numberOfSubarraysViaTwoPointers(int[] nums, int k) {
int left = 0;
int count = 0;
int subarraysSoFar = 0;
for (int right = 0; right < nums.length; right++) {
if (nums[right] % 2 != 0) {
k--;
subarraysSoFar = 0; // new odd found -> reset the counter
}
while (k == 0) {
k += nums[left] == 1 ? 1 : 0;
subarraysSoFar++;
left++;
}
count += subarraysSoFar;
}
return count;
}
}