[InterviewBit] Subarray with B odd numbers

Subarray with B odd numbers

  • Time :
  • Space :
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24

int Solution::solve(vector<int> &A, int B) {
if(B == 0) {
int now = 0;
int res = 0;
for(auto& a : A) {
if(a & 1) now = 0;
else now += 1;
res += now;
}
return res;
}
vector<int> st{-1};
for(int i = 0; i < A.size(); i++) if(A[i] & 1) st.push_back(i);
st.push_back(A.size());
int res = 0;
for(int i = B; i < st.size() - 1; i++) {
int l = st[i - B + 1] - st[i - B];
int r = st[i + 1] - st[i];
res += l * r;
}
return res;
}

Author: Song Hayoung
Link: https://songhayoung.github.io/2022/11/04/PS/interviewbit/subarray-with-b-odd-numbers/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.