class Solution:
def numOfSubarrays(self, arr):
MOD = 10**9 + 7
odd = even = 0
result = 0
for num in arr:
if num % 2 == 0:
even += 1
else:
# swap odd and even, then increment odd
odd, even = even, odd
odd += 1
result = (result + odd) % MOD
return result
class Solution {
public:
int numOfSubarrays(vector<int>& arr) {
int MOD = 1e9 + 7;
int odd = 0, even = 0, result = 0;
for (int num : arr) {
if (num % 2 == 0) {
even++;
} else {
int temp = odd;
odd = even + 1;
even = temp;
}
result = (result + odd) % MOD;
}
return result;
}
};
class Solution {
public int numOfSubarrays(int[] arr) {
int MOD = 1000000007;
int odd = 0, even = 0, result = 0;
for (int num : arr) {
if (num % 2 == 0) {
even++;
} else {
int temp = odd;
odd = even + 1;
even = temp;
}
result = (result + odd) % MOD;
}
return result;
}
}
var numOfSubarrays = function(arr) {
const MOD = 1e9 + 7;
let odd = 0, even = 0, result = 0;
for (let num of arr) {
if (num % 2 === 0) {
even++;
} else {
let temp = odd;
odd = even + 1;
even = temp;
}
result = (result + odd) % MOD;
}
return result;
};
arr
, count the number of contiguous subarrays whose sum is odd. The result should be returned modulo 10^9 + 7
due to potentially large output. Each subarray must have at least one element, and you should consider all possible contiguous subarrays.
odd
and even
, where odd
is the number of prefix sums with odd sum up to the current index, and even
is the number of prefix sums with even sum up to the current index.odd
count.odd
for each index to get the final answer.arr = [1, 3, 5]
:
odd = 0
, even = 0
, result = 0