[LeetCode] Number of Sub-arrays With Odd Sum

1524. Number of Sub-arrays With Odd Sum

Given an array of integers arr, return the number of subarrays with an odd sum.

Since the answer can be very large, return it modulo 109 + 7.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class Solution {
public:
int numOfSubarrays(vector<int>& arr) {
long long odd = 0, even = 1, sum = 0, res = 0, mod = 1e9 + 7;
for(auto& a : arr) {
sum += a;
if(sum & 1) {
res += even;
odd++;
} else {
res += odd;
even++;
}
res %= mod;
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/07/14/PS/LeetCode/number-of-sub-arrays-with-odd-sum/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.