-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSubArrayWithKOddNumbers.java
73 lines (58 loc) · 1.48 KB
/
SubArrayWithKOddNumbers.java
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
61
62
63
64
65
66
67
68
69
70
71
72
73
/*
Problem Description
Given an array of integers A and an integer B.
Find the total number of subarrays having exactly B odd numbers.
Problem Constraints
1 <= length of the array <= 10^5
1 <= A[i] <= 10^9
0 <= B <= A
Input Format
The first argument given is the integer array A.
The second argument given is integer B.
Output Format
Return the total number of subarrays having exactly B odd numbers.
Example Input
Input 1:
A = [4, 3, 2, 3, 4]
B = 2
Input 2:
A = [5, 6, 7, 8, 9]
B = 3
Example Output
Output 1:
4
Output 2:
1
Example Explanation
Explanation 1:
The subarrays having exactly B odd numbers are:
[4, 3, 2, 3], [4, 3, 2, 3, 4], [3, 2, 3], [3, 2, 3, 4]
Explanation 2:
The subarrays having exactly B odd numbers is [5, 6, 7, 8, 9]
*/
public class Solution {
public int solve(ArrayList<Integer> A, int B) {
HashMap<Integer,Integer> map = new HashMap<>();
int ans = 0;
int count = 0;
for(int i=0; i<A.size(); i++){
if(A.get(i) % 2 != 0){
count++;
}
int x = count - B;
if(map.containsKey(x)){
ans = ans + map.get(x);
}
if(count == B){
ans = ans + 1;
}
if(map.containsKey(count)){
map.put(count,map.get(count) + 1);
}
else{
map.put(count,1);
}
}
return ans;
}
}