703390. Find the number of subarrays having even sum
Here is a detailed Markdown blog post for the problem:
Find the number of subarrays having even sum #1533
Summary
This problem involves finding the number of subarrays in an array that have an even sum. The given array can contain both positive and negative integers, and we need to count the number of subarrays that have a total sum divisible by 2.
The key concepts involved are arrays, data structures, and algorithms.
Detailed Explanation
To solve this problem, we will iterate over all possible subarrays in the given array. For each subarray, we calculate its sum and check if it's even (i.e., divisible by 2). If the sum is even, we increment a counter to keep track of the number of such subarrays.
Here's a step-by-step breakdown of the solution:
- Initialize a variable
countto store the number of subarrays with even sums. - Iterate over all possible subarrays in the given array. For each subarray:
- Calculate its sum by iterating over its elements and adding them up.
- Check if the sum is even (i.e., divisible by 2).
- If the sum is even, increment the
countvariable.
- Return the final value of the
countvariable as the number of subarrays with even sums.
Time complexity: O(n^2), where n is the length of the given array. This is because we're iterating over all possible subarrays in the array, and each subarray has a maximum size of n.
Space complexity: O(1), as we only need to keep track of a single variable count.
Here's an ASCII art diagram illustrating the problem:
+---------------+
| Array [a, b, c] |
+---------------+
|
v
+---------------+ +---------------+
| Subarray [a] | | Subarray [b] |
| (sum = a) | | (sum = b) |
+---------------+ +---------------+
|
v
+---------------+ +---------------+
| Subarray [a, b]| | Subarray [c] |
| (sum = a+b) | | (sum = c) |
+---------------+ +---------------+
Optimized Solutions
Java
public int findSubarrays(int[] arr) {
int count = 0;
for (int i = 0; i < arr.length; i++) {
for (int j = i; j < arr.length; j++) {
int sum = 0;
for (int k = i; k <= j; k++) {
sum += arr[k];
}
if (sum % 2 == 0) {
count++;
}
}
}
return count;
}