1524. Number of Sub-arrays With Odd Sum #1359
-
Topics: Given an array of integers Since the answer can be very large, return it modulo Example 1:
Example 2:
Example 3:
Constraints:
Hint:
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
We need to determine the number of subarrays with an odd sum in an efficient manner. Directly calculating the sum of all possible subarrays would be computationally expensive, so we use a more optimized approach based on prefix sums and their parity (even or odd). Approach
Let's implement this solution in PHP: 1524. Number of Sub-arrays With Odd Sum <?php
/**
* @param Integer[] $arr
* @return Integer
*/
function numOfSubarrays($arr) {
$mod = 1000000007;
$even = 1; // starts with prefix sum 0 (even)
$odd = 0;
$result = 0;
$current_parity = 0; // initial prefix sum is 0 (even)
foreach ($arr as $num) {
$current_parity = ($current_parity + $num) % 2;
if ($current_parity == 1) {
$result = ($result + $even) % $mod;
} else {
$result = ($result + $odd) % $mod;
}
if ($current_parity == 1) {
$odd++;
} else {
$even++;
}
}
return $result % $mod;
}
// Test Cases
echo numOfSubarrays([1,3,5]) . "\n"; // Output: 4
echo numOfSubarrays([2,4,6]) . "\n"; // Output: 0
echo numOfSubarrays([1,2,3,4,5,6,7]) . "\n"; // Output: 16
?> Explanation:
This approach efficiently computes the number of subarrays with an odd sum in O(n) time complexity, making it suitable for large input sizes up to 100,000 elements. |
Beta Was this translation helpful? Give feedback.
We need to determine the number of subarrays with an odd sum in an efficient manner. Directly calculating the sum of all possible subarrays would be computationally expensive, so we use a more optimized approach based on prefix sums and their parity (even or odd).
Approach