Maximum length of subarray such that sum of the subarray is even in C++


We are given with an array Arr[] of integers. The goal is to find longest length subarray of Arr[] , sum of whose elements is even. That is, the sum of elements of a subarray is even and that subarray is longest in length.

Input − Arr[] = { 2,3,5,2,6,7 }.

Output −Maximum length of subarray − 4

Explanation −The maximum length subarray is { 5,2,6,7 }. Sum is 20 which is even.

Input − Arr[] = { 5,7,7,3,4 }.

Output − Maximum length of subarray − 4

Explanation − The maximum length subarray is { 5,7,7,3 }. Sum is 22 which is even.

Approach used in the below program is as follows

  • The integer array Arr[] is used to store the integers.

  • Variable size is used to store the length of the array.

  • Function Length( int arr[] ) is check the sum of arrays is even. Leng is used to store the length of subarray.

  • Calculate whole sum of array, if even return length of array, n.

  • Now starting from the first element, traverse the whole array, if an odd element is found then find the length of both halfs excluding arr[i].

  • Return the max length for the length of the subarray.

Example

 Live Demo

#include<iostream<
int Length(int arr[], int n){
   int sum = 0, leng = 0;
   // if whole array is even
   for (int i = 0; i < n; i++)
      sum += arr[i];
   if (sum % 2 == 0) // total sum is already even
      return n;
   // Find an index i such the a[i] is odd
   // and compare length of both halfs excluding
   // a[i] to find max length subarray
   for (int i = 0; i < n; i++) {
      if (arr[i] % 2 == 1)
         leng = i>n-i-1?i:n-i-1;
   }
   return leng;
}
int main(){
   int Arr[] = { 1, 2, 6, 2, 4,2 };
   int size = 6;
   printf("Maximum length of subarray such that sum of the subarray is even: %d",Length(Arr, size));
return 0;
}

Output

If we run the above code it will generate the following output −

Maximum length of subarray such that sum of the subarray is even : 5

Updated on: 17-Aug-2020

563 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements