Find number of subarrays with even sum in C++


In this problem, we are given an array arr[] consisting of N elements. Our task is to find the subarray with even sum.

Let’s take an example to understand the problem,

Input

arr[] = {2, 1, 3, 4, 2, 5}

Output

28

Explanation

The subarrays are −

{2}, {4}, {2}, {2, 4}, {2, 2}, {1, 3}, {1, 5}, {3, 5}, {4, 2}, {2, 1, 3}, {2, 1, 5}, {2, 3, 5}, {2, 4, 2}, {1, 3, 4}, {1, 3, 2}, {1, 4, 5}, {1, 2, 5}, {3, 4, 5}, {3, 2, 5}, {2, 1, 3, 4}, {2, 1, 3, 2}, {2, 3, 4, 5}, {2, 3, 2, 5}, {2, 4, 2, 5}, {1, 3, 4, 2}, {1, 4, 2, 5}, {3, 4, 2, 5}, {2, 1, 3, 4, 2}, {2, 1, 3, 4, 2, 5}

Solution Approach

A simple solution to the problem is using the direct method which is by calculating all subarray and their sums. And the increase count for the subarray with even sum. And at last return count.

Program to illustrate the working of our solution,

Example

 Live Demo

#include<iostream>
using namespace std;
int countEvenSumSubArray(int arr[], int n){
   int evenSumCount = 0, sum = 0;
   for (int i=0; i<=n-1; i++){
      sum = 0;
      for (int j=i; j<=n-1; j++){
         sum += arr[j];
      if (sum % 2 == 0)
         evenSumCount++;
      }
   }
   return (evenSumCount);
}
int main(){
   int arr[] = {2, 1, 4, 2};
   int n = sizeof (arr) / sizeof (arr[0]);
   cout<<"The count of Subarrays with even sum is "<<countEvenSumSubArray(arr, n);
   return (0);
}

Output

The number of solutions of the linear equation is 8

Updated on: 15-Mar-2021

221 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements