[LeetCode] Number of Subarrays Having Even Product

2495. Number of Subarrays Having Even Product

Given a 0-indexed integer array nums, return the number of subarrays of nums having an even product.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class Solution {
public:
long long evenProduct(vector<int>& nums) {
long long res = 0;
vector<int> pos;
for(int i = 0; i < nums.size(); i++) {
if(nums[i] % 2) continue;
pos.push_back(i);
}
pos.push_back(nums.size());
for(int i = 0; i < pos.size() - 1; i++) {
res += (pos[i] + 1ll) * (pos[i+1] - pos[i]);
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/12/21/PS/LeetCode/number-of-subarrays-having-even-product/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.