Length of longest Subarray with equal number of odd and even elements
Last Updated :
11 Oct, 2023
Given an integer array arr[], the task is to find the length of the longest subarray with an equal number of odd and even elements.
Examples:
Input: arr[] = {1, 2, 1, 2}
Output: 4
Explanation:
Subarrays in the given array are –
{{1}, {1, 2}, {1, 2, 1}, {1, 2, 1, 2}, {2}, {2, 1}, {2, 1, 2}, {1}, {1, 2}, {2}}
where the length of the longest subarray with an equal number of even and odd elements is 4 – {1, 2, 1, 2}
Input: arr[] = {12, 4, 7, 8, 9, 2, 11, 0, 2, 13}
Output: 8
Naive Approach: Simple solution is to consider all subarrays one by one and check the count of even and odd elements in the subarray. Then find the maximum length of those subarray that contain an equal number of even elements and odd elements.
Steps to implement-
- Initialize a variable ans to store the final answer
- Run two loops to find all subarrays and simultaneously find their length
- After that count number of odd elements and the number of even elements in that
- If that subarray contains an equal number of odd and even elements then
- Update ans with maximum of ans and the length of that subarray
Code-
C++
#include <bits/stdc++.h>
using namespace std;
int maxSubarrayLength( int arr[], int N)
{
int ans=0;
for ( int i=0;i<N;i++){
int length=0;
for ( int j=i;j<N;j++){
length++;
int even=0;
int odd=0;
for ( int k=i;k<=j;k++){
if (arr[k]%2==0){even++;}
else if (arr[k]%2==1){odd++;}
}
if (odd==even){
ans=max(ans,length);
}
}
}
return ans;
}
int main()
{
int arr[] = { 12, 4, 7, 8, 9, 2,
11, 0, 2, 13 };
int n = sizeof (arr) / sizeof (arr[0]);
cout << maxSubarrayLength(arr, n);
return 0;
}
|
Java
import java.util.*;
public class Main {
static int maxSubarrayLength( int [] arr, int N)
{
int ans = 0 ;
for ( int i = 0 ; i < N; i++) {
int length = 0 ;
for ( int j = i; j < N; j++) {
length++;
int even = 0 ;
int odd = 0 ;
for ( int k = i; k <= j; k++) {
if (arr[k] % 2 == 0 ) {
even++;
}
else if (arr[k] % 2 == 1 ) {
odd++;
}
}
if (odd == even) {
ans = Math.max(ans, length);
}
}
}
return ans;
}
public static void main(String[] args)
{
int [] arr = { 12 , 4 , 7 , 8 , 9 , 2 , 11 , 0 , 2 , 13 };
int n = arr.length;
System.out.println(maxSubarrayLength(arr, n));
}
}
|
Python
def maxSubarrayLength(arr, N):
ans = 0
for i in range (N):
length = 0
for j in range (i, N):
length + = 1
even = 0
odd = 0
for k in range (i, j + 1 ):
if arr[k] % 2 = = 0 :
even + = 1
elif arr[k] % 2 = = 1 :
odd + = 1
if odd = = even:
ans = max (ans, length)
return ans
if __name__ = = "__main__" :
arr = [ 12 , 4 , 7 , 8 , 9 , 2 , 11 , 0 , 2 , 13 ]
n = len (arr)
print (maxSubarrayLength(arr, n))
|
C#
using System;
class GFG
{
static int MaxSubarrayLength( int [] arr, int N)
{
int ans = 0;
for ( int i = 0; i < N; i++)
{
int length = 0;
for ( int j = i; j < N; j++)
{
length++;
int even = 0;
int odd = 0;
for ( int k = i; k <= j; k++)
{
if (arr[k] % 2 == 0)
{
even++;
}
else if (arr[k] % 2 == 1)
{
odd++;
}
}
if (odd == even)
{
ans = Math.Max(ans, length);
}
}
}
return ans;
}
static void Main()
{
int [] arr = { 12, 4, 7, 8, 9, 2, 11, 0, 2, 13 };
int n = arr.Length;
Console.WriteLine(MaxSubarrayLength(arr, n));
}
}
|
Javascript
function maxSubarrayLength(arr, N)
{
let ans=0;
for (let i=0;i<N;i++){
let length=0;
for (let j=i;j<N;j++){
length++;
let even=0;
let odd=0;
for (let k=i;k<=j;k++){
if (arr[k]%2==0){even++;}
else if (arr[k]%2==1){odd++;}
}
if (odd==even){
ans=Math.max(ans,length);
}
}
}
return ans;
}
var arr = [12, 4, 7, 8, 9, 2,
11, 0, 2, 13 ];
var n = arr.length;
console.log(maxSubarrayLength(arr, n));
|
Time Complexity: O(N3), because of two nested loops to find all subarrays and a third loop to find the number of odd and even elements in a subarray
Auxiliary Space: O(1), because no extra space has been used
Efficient Approach: The idea is to consider the odd elements as 1 and even elements as -1 and return the length of the longest sub-array with the sum equal to 0. The subarray with a given sum can be found using this method.
Time Complexity: O(N)
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
int maxSubarrayLength( int * A, int N)
{
int maxLen = 0;
int curr_sum = 0;
unordered_map< int , int > hash;
for ( int i = 0; i < N; i++) {
if (A[i] % 2 == 0)
curr_sum -= 1;
else
curr_sum += 1;
if (curr_sum == 0)
maxLen = max(maxLen, i + 1);
if (hash.find(curr_sum) != hash.end())
maxLen = max(maxLen,
i - hash[curr_sum]);
else
hash[curr_sum] = i;
}
return maxLen;
}
int main()
{
int arr[] = { 12, 4, 7, 8, 9, 2,
11, 0, 2, 13 };
int n = sizeof (arr) / sizeof (arr[0]);
cout << maxSubarrayLength(arr, n);
return 0;
}
|
Java
import java.util.*;
class GFG
{
static int maxSubarrayLength( int []A, int N)
{
int maxLen = 0 ;
int curr_sum = 0 ;
HashMap<Integer,Integer> hash = new HashMap<Integer,Integer>();
for ( int i = 0 ; i < N; i++)
{
if (A[i] % 2 == 0 )
curr_sum -= 1 ;
else
curr_sum += 1 ;
if (curr_sum == 0 )
maxLen = Math.max(maxLen, i + 1 );
if (hash.containsKey(curr_sum))
maxLen = Math.max(maxLen,
i - hash.get(curr_sum));
else {
hash.put(curr_sum, i);
}
}
return maxLen;
}
public static void main(String[] args)
{
int arr[] = { 12 , 4 , 7 , 8 , 9 , 2 ,
11 , 0 , 2 , 13 };
int n = arr.length;
System.out.print(maxSubarrayLength(arr, n));
}
}
|
Python3
def maxSubarrayLength(A, N) :
maxLen = 0 ;
curr_sum = 0 ;
hash = {};
for i in range (N) :
if (A[i] % 2 = = 0 ) :
curr_sum - = 1 ;
else :
curr_sum + = 1 ;
if (curr_sum = = 0 ) :
maxLen = max (maxLen, i + 1 );
if curr_sum in hash :
maxLen = max (maxLen, i - hash [curr_sum]);
else :
hash [curr_sum] = i;
return maxLen;
if __name__ = = "__main__" :
arr = [ 12 , 4 , 7 , 8 , 9 , 2 , 11 , 0 , 2 , 13 ];
n = len (arr);
print (maxSubarrayLength(arr, n));
|
C#
using System;
using System.Collections.Generic;
class GFG
{
static int maxSubarrayLength( int []A, int N)
{
int maxLen = 0;
int curr_sum = 0;
Dictionary< int , int > hash = new Dictionary< int , int >();
for ( int i = 0; i < N; i++)
{
if (A[i] % 2 == 0)
curr_sum -= 1;
else
curr_sum += 1;
if (curr_sum == 0)
maxLen = Math.Max(maxLen, i + 1);
if (hash.ContainsKey(curr_sum))
maxLen = Math.Max(maxLen,
i - hash[curr_sum]);
else {
hash.Add(curr_sum, i);
}
}
return maxLen;
}
public static void Main(String[] args)
{
int []arr = { 12, 4, 7, 8, 9, 2,
11, 0, 2, 13 };
int n = arr.Length;
Console.Write(maxSubarrayLength(arr, n));
}
}
|
Javascript
<script>
function maxSubarrayLength(A, N)
{
var maxLen = 0;
var curr_sum = 0;
var hash = new Map();
for ( var i = 0; i < N; i++) {
if (A[i] % 2 == 0)
curr_sum -= 1;
else
curr_sum += 1;
if (curr_sum == 0)
maxLen = Math.max(maxLen, i + 1);
if (hash.has(curr_sum))
maxLen = Math.max(maxLen,
i - hash.get(curr_sum));
else
hash.set(curr_sum, i);
}
return maxLen;
}
var arr = [12, 4, 7, 8, 9, 2,
11, 0, 2, 13 ];
var n = arr.length;
document.write( maxSubarrayLength(arr, n));
</script>
|
Time Complexity: O(n)
Auxiliary Space: O(n), where n is the size of the given array.
Share your thoughts in the comments
Please Login to comment...