Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Interview Questions on Array
  • Practice Array
  • MCQs on Array
  • Tutorial on Array
  • Types of Arrays
  • Array Operations
  • Subarrays, Subsequences, Subsets
  • Reverse Array
  • Static Vs Arrays
  • Array Vs Linked List
  • Array | Range Queries
  • Advantages & Disadvantages
Open In App
Next Article:
Sum of all odd length subarrays
Next article icon

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

Last Updated : 19 Apr, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Given an array of N elements. The task is to find the length of the longest subarray such that sum of the subarray is even.
Examples: 

Input : N = 6, arr[] = {1, 2, 3, 2, 1, 4}
Output : 5
Explanation: In the example the subarray
in range [2, 6] has sum 12 which is even,
so the length is 5.
Input : N = 4, arr[] = {1, 2, 3, 2}
Output : 4
Recommended: Please try your approach on {IDE} first, before moving on to the solution.

Naive Approach

The idea is to find all subarrays and then find those subarrays whose sum of elements are even. After that choose the longest length of those subarrays.

Steps to implement-

  • Declare a variable ans with value 0 to store the final answer
  • Run two loops to find all subarrays
  • Find the sum of all elements of the subarray
  • When the sum of all elements of the subarray is even 
    • Then update ans as the maximum of ans and the length of that subarray

Code-

C++
// C++ implementation of the above approach #include <bits/stdc++.h> using namespace std;  // Function to find length of the longest // subarray such that sum of the // subarray is even int maxLength(int arr[], int N) {    //To store answer    int ans=0;        //Find all subarray    for(int i=0;i<N;i++){        //To store length of subarray        int length=0;        for(int j=i;j<N;j++){            //Increment the length            length++;                        //Boolean variable to tell whether sum             //of all elements are even or not            bool val=false;                        //To store sum of all elements of subarray            int sum=0;                        for(int k=i;k<=j;k++){                sum+=arr[k];            }                        //When sum of all elements are even            if(sum%2==0){                ans=max(ans,length);            }        }    }    return ans; }  // Driver Code int main() {     int arr[] = { 1, 2, 3, 2 };     int N = sizeof(arr) / sizeof(arr[0]);      cout << maxLength(arr, N) << "\n";      return 0; } 
Java
// Java implementation of the above approach import java.util.*;  public class Main {      // Function to find length of the longest     // subarray such that sum of the     // subarray is even     static int maxLength(int[] arr, int N) {         // To store answer         int ans = 0;          // Find all subarray         for (int i = 0; i < N; i++) {             // To store length of subarray             int length = 0;             for (int j = i; j < N; j++) {                 // Increment the length                 length++;                  // Boolean variable to tell whether sum                 // of all elements are even or not                 boolean val = false;                  // To store sum of all elements of subarray                 int sum = 0;                  for (int k = i; k <= j; k++) {                     sum += arr[k];                 }                  // When sum of all elements is even                 if (sum % 2 == 0) {                     ans = Math.max(ans, length);                 }             }         }         return ans;     }      // Driver Code     public static void main(String[] args) {         int[] arr = {1, 2, 3, 2};         int N = arr.length;          System.out.println(maxLength(arr, N));     } }  // This code is contributed by Pushpesh Raj 
Python3
# Python3 implementation of the above approach  # Function to find length of the longest subarray such  # that sum of the subarray is even def maxLength(arr):     # To store the answer     ans = 0      # Find all subarrays     for i in range(len(arr)):         # To store the length of subarray         length = 0         for j in range(i, len(arr)):             # Increment the length             length += 1              # Boolean variable to tell whether the sum              # of all elements is even or not             val = False              # To store the sum of all elements of subarray             subarray_sum = 0              for k in range(i, j + 1):                 subarray_sum += arr[k]              # When the sum of all elements is even             if subarray_sum % 2 == 0:                 ans = max(ans, length)      return ans  # Driver Code arr = [1, 2, 3, 2] print(maxLength(arr)) 
C#
using System;  public class GFG {     // Function to find length of the longest     // subarray such that sum of the     // subarray is even     public static int MaxLength(int[] arr, int N)     {         // To store the answer         int ans = 0;          // Find all subarrays         for (int i = 0; i < N; i++)         {             // To store the length of subarray             int length = 0;             for (int j = i; j < N; j++)             {                 // Increment the length                 length++;                  // To store the sum of all elements of subarray                 int sum = 0;                  for (int k = i; k <= j; k++)                 {                     sum += arr[k];                 }                  // When the sum of all elements is even                 if (sum % 2 == 0)                 {                     ans = Math.Max(ans, length);                 }             }         }         return ans;     }      // Driver code     public static void Main(string[] args)     {         int[] arr = { 1, 2, 3, 2 };         int N = arr.Length;          Console.WriteLine(MaxLength(arr, N));     } } 
JavaScript
function MaxLength(arr, N) {     // To store the answer     let ans = 0;      // Find all subarrays     for (let i = 0; i < N; i++) {         // To store the length of subarray         let length = 0;         for (let j = i; j < N; j++) {             // Increment the length             length++;              // To store the sum of all elements of subarray             let sum = 0;              for (let k = i; k <= j; k++) {                 sum += arr[k];             }              // When the sum of all elements is even             if (sum % 2 === 0) {                 ans = Math.max(ans, length);             }         }     }     return ans; }  // Driver code const arr = [1, 2, 3, 2]; const N = arr.length;  console.log(MaxLength(arr, N)); 

Output
4 

Time Complexity: O(N3), because of two nested loops to find all subarray and third loop is to find the sum of all elements of subarray
Auxiliary Space: O(1), because no extra space has been used


Approach: First check if the total sum of the array is even. If the total sum of the array is even then the answer will be N.
If the total sum of the array is not even, means it is ODD. So, the idea is to find an odd element from the array such that excluding that element and comparing the length of both parts of the array we can obtain the max length of the subarray with even sum.
It is obvious that the subarray with even sum will exist in range [1, x) or (x, N], 
where 1 <= x <= N, and arr[x] is ODD. 
Below is the implementation of above approach: 

C++
// C++ implementation of the above approach  #include <bits/stdc++.h> using namespace std;  // Function to find length of the longest // subarray such that sum of the // subarray is even int maxLength(int a[], int n) {     int sum = 0, len = 0;      // Check if sum of complete array is even     for (int i = 0; i < n; i++)         sum += a[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 halves excluding     // a[i] to find max length subarray     for (int i = 0; i < n; i++) {         if (a[i] % 2 == 1)             len = max(len, max(n - i - 1, i));     }      return len; }  // Driver Code int main() {     int a[] = { 1, 2, 3, 2 };     int n = sizeof(a) / sizeof(a[0]);      cout << maxLength(a, n) << "\n";      return 0; } 
Java
// Java implementation of the approach  class GFG  {      // Function to find length of the longest     // subarray such that sum of the     // subarray is even     static int maxLength(int a[], int n)     {         int sum = 0, len = 0;          // Check if sum of complete array is even         for (int i = 0; i < n; i++)         {             sum += a[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 (a[i] % 2 == 1)             {                 len = Math.max(len, Math.max(n - i - 1, i));             }         }          return len;     }      // Driver Code     public static void main(String[] args)     {         int a[] = {1, 2, 3, 2};         int n = a.length;         System.out.println(maxLength(a, n));      } }  // This code has been contributed by 29AjayKumar 
Python
# Python3 implementation of the above approach  # Function to find Length of the longest # subarray such that Sum of the # subarray is even def maxLength(a, n):      Sum = 0     Len = 0      # Check if Sum of complete array is even     for i in range(n):         Sum += a[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 i in range(n):         if (a[i] % 2 == 1):             Len = max(Len, max(n - i - 1, i))      return Len  # Driver Code  a= [1, 2, 3, 2] n = len(a)  print(maxLength(a, n))  # This code is contributed by mohit kumar 
C#
// C# implementation of the approach using System;  class GFG {          // Function to find length of the longest     // subarray such that sum of the     // subarray is even     static int maxLength(int []a, int n)     {         int sum = 0, len = 0;          // Check if sum of complete array is even         for (int i = 0; i < n; i++)         {             sum += a[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 (a[i] % 2 == 1)             {                 len = Math.Max(len, Math.Max(n - i - 1, i));             }         }          return len;     }      // Driver Code     static public void Main ()     {         int []a = {1, 2, 3, 2};         int n = a.Length;         Console.WriteLine(maxLength(a, n));      } }  // This code has been contributed by ajit. 
JavaScript
<script>  // Javascript implementation of the above approach   // Function to find length of the longest  // subarray such that sum of the  // subarray is even  function maxLength(a, n)  {      let sum = 0, len = 0;       // Check if sum of complete array is even      for (let i = 0; i < n; i++)          sum += a[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 (let i = 0; i < n; i++) {          if (a[i] % 2 == 1)              len = Math.max(len, Math.max(n - i - 1, i));      }       return len;  }   // Driver Code      let a = [ 1, 2, 3, 2 ];      let n = a.length;       document.write(maxLength(a, n) + "<br>");        // This code is contributed by Mayank Tyagi  </script> 
PHP
<?php //PHP implementation of the above approach  // Function to find length of the longest // subarray such that sum of the // subarray is even function maxLength($a, $n) {     $sum = 0;     $len = 0;      // Check if sum of complete array is even     for ($i = 0; $i < $n; $i++)         $sum += $a[$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 ($i = 0; $i < $n; $i++)      {         if ($a[$i] % 2 == 1)             $len = max($len, $max($n - $i - 1, $i));     }      return $len; }  // Driver Code $a = array (1, 2, 3, 2 ); $n = count($a);  echo maxLength($a, $n) , "\n";   // This code is contributed by akt_mit. ?> 

Output
4 

Time Complexity: O(N)
Auxiliary Space: O(1)



Next Article
Sum of all odd length subarrays

S

souradeep
Improve
Article Tags :
  • Analysis of Algorithms
  • Arrays
  • C++ Programs
  • DSA
  • Mathematical
  • subarray
  • subarray-sum
Practice Tags :
  • Arrays
  • Mathematical

Similar Reads

  • C++ Program for Size of The Subarray With Maximum Sum
    An array is given, find length of the subarray having maximum sum. Examples : Input : a[] = {1, -2, 1, 1, -2, 1} Output : Length of the subarray is 2 Explanation: Subarray with consecutive elements and maximum sum will be {1, 1}. So length is 2 Input : ar[] = { -2, -3, 4, -1, -2, 1, 5, -3 } Output :
    4 min read
  • Longest unique subarray of an Array with maximum sum in another Array
    Given two arrays X[] and Y[] of size N, the task is to find the longest subarray in X[] containing only unique values such that a subarray with similar indices in Y[] should have a maximum sum. The value of array elements is in the range [0, 1000]. Examples: Input: N = 5, X[] = {0, 1, 2, 0, 2}, Y[]
    10 min read
  • Sum of all odd length subarrays
    Given an array arr[] consisting of N integers, the task is to find the sum of all the elements of all possible subarrays of odd length. Examples: Input: arr[] = {3, 2, 4}Output: 18Explanation:The odd length subarrays along with their sum are as follows:1) {3} = sum is 3.2) {2} = sum is 2.3) {4} = su
    9 min read
  • Length of longest subarray whose sum is not divisible by integer K
    Given an array arr[] of size N and an integer k, our task is to find the length of longest subarray whose sum of elements is not divisible by k. If no such subarray exists then return -1.Examples: Input: arr[] = {8, 4, 3, 1, 5, 9, 2}, k = 2 Output: 5 Explanation: The subarray is {8, 4, 3, 1, 5} with
    10 min read
  • Sum of Max of Subarrays
    Given an array arr[], the task is to find the sum of the maximum elements of every possible non-empty sub-arrays of the given array arr[]. Examples: Input: arr[] = [1, 3, 2]Output: 15Explanation: All possible non-empty subarrays of [1, 3, 2] are {1}, {3}, {2}, {1, 3}, {3, 2} and {1, 3, 2}. The maxim
    12 min read
  • Maximum of XOR of first and second maximum of all subarrays
    Given an array arr[] of distinct elements, the task is to find the maximum of XOR value of the first and second maximum elements of every possible subarray.Note: Length of the Array is greater than 1. Examples: Input: arr[] = {5, 4, 3} Output: 7 Explanation: All Possible subarrays with length greate
    11 min read
  • Maximum length sub-array which satisfies the given conditions
    Given an array arr[] of N integers, the task is to find the maximum length of any sub-array of arr[] which satisfies one of the given conditions: The subarray is strictly increasing.The subarray is strictly decreasing.The subarray is first strictly increasing then strictly decreasing. Examples: Inpu
    9 min read
  • Rearrange array elements excluded by given ranges to maximize sum of subarrays starting from the first index
    Given an array arr[] consisting of N integers and an array Q[][], where each row denotes a range {l, r}(0 ? l ? r ? N - 1). The task is to find the maximum sum of all subarrays starting from index 0 by rearranging the array except the elements in the ranges given in Q[][]. Examples: Input: arr[] = {
    10 min read
  • Maximum Sum SubArray using Divide and Conquer | Set 2
    Given an array arr[] of integers, the task is to find the maximum sum sub-array among all the possible sub-arrays.Examples: Input: arr[] = {-2, 1, -3, 4, -1, 2, 1, -5, 4} Output: 6 {4, -1, 2, 1} is the required sub-array.Input: arr[] = {2, 2, -2} Output: 4 Approach: Till now we are only aware of Kad
    13 min read
  • Check if its possible to make sum of the array odd with given Operations
    Given an array arr[], the task is to check if it is possible to make the sum of array odd such that any two indices i and j can be chosen and arr[i] can be set equal to arr[j] given that i != j. Examples: Input: arr[] = { 5, 4, 4, 5, 1, 3 } Output: Yes Explanation: The sum of the array is 22. Put ar
    7 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences