Longest subarray with all even or all odd elements

13 Aug, 2021
Given an array A[ ] of N non-negative integers, the task is to find the length of the longest sub-array such that all the elements in that sub-array are odd or even.
Examples:
Input: A[] = {2, 5, 7, 2, 4, 6, 8, 3}Output: 4Explanation: Sub-array {2, 4, 6, 8} of length 4 has all even elements
Input: A[] = {2, 3, 2, 5, 7, 3} Output: 3Explanation: Sub-array {5, 7, 3} of length 3 has all odd elements  
Naive Approach: A naive approach to solve this problem is to consider all the contiguous sub-arrays and for each sub-array, check if all the elements are even or odd. The longest of them will be the answer.Time Complexity: O(N^2)Auxiliary Space: O(1)
Efficient Approach: The main idea to solve this problem is to use Dynamic Programming(it has both the properties – Optimal Substructure and Overlapping Subproblems) such that if there are some contiguous odd elements, then the very next odd element will increase the length of that contiguous array by one. And this is also true for even elements. Follow the steps below to solve the problem: 
Initialize an array dp[ ] where dp[i] stores the length of sub-array that ends at A[i].
Initialize dp[0] with 1.
Initialize the variable ans as 1 to store the answer.
Iterate over the range [1, N] using the variable i and perform the following steps:If A[i]%2 is equal to A[i-1]%2, then set the value of dp[i] as dp[i-1]+1.Else, set the value of dp[i] as 1.
If A[i]%2 is equal to A[i-1]%2, then set the value of dp[i] as dp[i-1]+1.
Else, set the value of dp[i] as 1.
Iterate over the range [0, N] using the variable i and perform the following steps:Set the value of ans as the maximum of ans or dp[i].
Set the value of ans as the maximum of ans or dp[i].
After performing the above steps, print the value of ans as the answer.
Below is the implementation of the above approach:
C++
Java
C#
Python3
Javascript
// C++ implementation for the above approach#include <bits/stdc++.h>using namespace std; // Function to calculate longest substring// with odd or even elementsint LongestOddEvenSubarray(int A[], int N){    // Initializing dp[]    int dp[N];     // Initializing dp[0] with 1    dp[0] = 1;     // ans will store the final answer    int ans = 1;     // Traversing the array from index 1 to N - 1    for (int i = 1; i < N; i++) {         // Checking both current and previous element        // is even or odd        if ((A[i] % 2 == 0 && A[i - 1] % 2 == 0)            || (A[i] % 2 != 0 && A[i - 1] % 2 != 0)) {             // Updating dp[i] with dp[i-1] + 1            dp[i] = dp[i - 1] + 1;        }        else            dp[i] = 1;    }     for (int i = 0; i < N; i++)        // Storing max element to ans        ans = max(ans, dp[i]);     // Returning the final answer    return ans;} // Driver Codeint main(){    // Input    int A[] = { 2, 5, 7, 2, 4, 6, 8, 3 };    int N = sizeof(A) / sizeof(A[0]);     // Function call    cout << LongestOddEvenSubarray(A, N);     return 0;}
// Java program for the above approachimport java.io.*; class GFG {     // Function to calculate longest substring    // with odd or even elements    static int LongestOddEvenSubarray(int A[], int N)    {               // Initializing dp[]        int dp[] = new int[N];         // Initializing dp[0] with 1        dp[0] = 1;         // ans will store the final answer        int ans = 1;         // Traversing the array from index 1 to N - 1        for (int i = 1; i < N; i++) {             // Checking both current and previous element            // is even or odd            if ((A[i] % 2 == 0 && A[i - 1] % 2 == 0)                || (A[i] % 2 != 0 && A[i - 1] % 2 != 0)) {                 // Updating dp[i] with dp[i-1] + 1                dp[i] = dp[i - 1] + 1;            }            else                dp[i] = 1;        }         for (int i = 0; i < N; i++)            // Storing max element to ans            ans = Math.max(ans, dp[i]);         // Returning the final answer        return ans;    }     // Driver Code    public static void main(String[] args)    {        // Input        int A[] = { 2, 5, 7, 2, 4, 6, 8, 3 };        int N = A.length;         // Function call        System.out.println(LongestOddEvenSubarray(A, N));    }} // This code is contributed by Potta Lokesh
// C# program for the above approachusing System; class GFG{     // Function to calculate longest substring    // with odd or even elements    static int LongestOddEvenSubarray(int[] A, int N)    {               // Initializing dp[]        int[] dp = new int[N];         // Initializing dp[0] with 1        dp[0] = 1;         // ans will store the final answer        int ans = 1;         // Traversing the array from index 1 to N - 1        for (int i = 1; i < N; i++) {             // Checking both current and previous element            // is even or odd            if ((A[i] % 2 == 0 && A[i - 1] % 2 == 0)                || (A[i] % 2 != 0 && A[i - 1] % 2 != 0)) {                 // Updating dp[i] with dp[i-1] + 1                dp[i] = dp[i - 1] + 1;            }            else                dp[i] = 1;        }         for (int i = 0; i < N; i++)                       // Storing max element to ans            ans = Math.Max(ans, dp[i]);         // Returning the final answer        return ans;    } // Driver Codepublic static void Main(){    // Input        int[] A = { 2, 5, 7, 2, 4, 6, 8, 3 };        int N = A.Length;         // Function call        Console.Write(LongestOddEvenSubarray(A, N));}} // This code is contributed by target_2.
# Python 3 implementation for the above approach # Function to calculate longest substring# with odd or even elementsdef LongestOddEvenSubarray(A, N):    # Initializing dp[]    dp = [0 for i in range(N)]     # Initializing dp[0] with 1    dp[0] = 1     # ans will store the final answer    ans = 1     # Traversing the array from index 1 to N - 1    for i in range(1, N, 1):               # Checking both current and previous element        # is even or odd        if ((A[i] % 2 == 0 and A[i - 1] % 2 == 0) or (A[i] % 2 != 0 and A[i - 1] % 2 != 0)):                         # Updating dp[i] with dp[i-1] + 1            dp[i] = dp[i - 1] + 1        else:            dp[i] = 1     for i in range(N):        # Storing max element to ans        ans = max(ans, dp[i])     # Returning the final answer    return ans # Driver Codeif __name__ == '__main__':    # Input    A = [2, 5, 7, 2, 4, 6, 8, 3]    N = len(A)     # Function call    print(LongestOddEvenSubarray(A, N))         # This code is contributed by SURENDRA_GANGWAR.
<script> // JavaScript implementation for the above approach // Function to calculate longest substring// with odd or even elementsfunction LongestOddEvenSubarray(A, N){   // Initializing dp[]  let dp = new Array(N);   // Initializing dp[0] with 1  dp[0] = 1;   // ans will store the final answer  let ans = 1;   // Traversing the array from index 1 to N - 1  for (let i = 1; i < N; i++)  {       // Checking both current and previous element    // is even or odd    if (      (A[i] % 2 == 0 && A[i - 1] % 2 == 0) ||      (A[i] % 2 != 0 && A[i - 1] % 2 != 0)    ) {      // Updating dp[i] with dp[i-1] + 1      dp[i] = dp[i - 1] + 1;    } else dp[i] = 1;  }   for (let i = 0; i < N; i++)       // Storing max element to ans    ans = Math.max(ans, dp[i]);   // Returning the final answer  return ans;} // Driver Code// Inputlet A = [2, 5, 7, 2, 4, 6, 8, 3];let N = A.length; // Function calldocument.write(LongestOddEvenSubarray(A, N)); // This code is contributed by _saurabh_jaiswal.</script>
4
Time Complexity: O(N)Auxiliary Space: O(N)
Space Optimization:  It is possible to further optimize the space complexity of the above approach by observing that, for calculating dp[i], only the value of dp[i-1] is relevant. So, store dp[i-1] in a variable and update the variable in each iteration. Also, update the answer in each iteration. Follow the steps below to solve the problem: 
Initialize the variables dp as 1 to store the length of the sub-array till i-1 and ans as 1 to store the answer.
Iterate over the range [1, N] using the variable i and perform the following steps:If A[i]%2 is equal to A[i-1]%2, then set the value of dp as dp+1 and set the value of ans as the maximum of ans or dp.Else, set the value of dp as 1.
If A[i]%2 is equal to A[i-1]%2, then set the value of dp as dp+1 and set the value of ans as the maximum of ans or dp.
Else, set the value of dp as 1.
After performing the above steps, print the value of ans as the answer.
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ implementation for the above approach#include <bits/stdc++.h>using namespace std; // Function to calculate longest substring// with odd or even elementsint LongestOddEvenSubarray(int A[], int N){    // Initializing dp    int dp;     // Initializing dp with 1    dp = 1;     // ans will store the final answer    int ans = 1;     // Traversing the array from index 1 to N - 1    for (int i = 1; i < N; i++) {         // Checking both current and previous element        // is even or odd        if ((A[i] % 2 == 0 && A[i - 1] % 2 == 0)            || (A[i] % 2 != 0 && A[i - 1] % 2 != 0)) {             // Updating dp with (previous dp value) + 1            dp = dp + 1;             // Storing max element so far to ans            ans = max(ans, dp);        }        else            dp = 1;    }     // Returning the final answer    return ans;} // Driver codeint main(){    // Input    int A[] = { 2, 5, 7, 2, 4, 6, 8, 3 };    int N = sizeof(A) / sizeof(A[0]);     // Function call    cout << LongestOddEvenSubarray(A, N);     return 0;}
// Java implementation for the above approachimport java.util.*;class GFG{ // Function to calculate longest subString// with odd or even elementsstatic int LongestOddEvenSubarray(int A[], int N){       // Initializing dp    int dp;     // Initializing dp with 1    dp = 1;     // ans will store the final answer    int ans = 1;     // Traversing the array from index 1 to N - 1    for (int i = 1; i < N; i++) {         // Checking both current and previous element        // is even or odd        if ((A[i] % 2 == 0 && A[i - 1] % 2 == 0)            || (A[i] % 2 != 0 && A[i - 1] % 2 != 0)) {             // Updating dp with (previous dp value) + 1            dp = dp + 1;             // Storing max element so far to ans            ans = Math.max(ans, dp);        }        else            dp = 1;    }     // Returning the final answer    return ans;} // Driver codepublic static void main(String[] args){       // Input    int A[] = { 2, 5, 7, 2, 4, 6, 8, 3 };    int N = A.length;     // Function call    System.out.print(LongestOddEvenSubarray(A, N));}} // This code is contributed by Amit Katiyar
# Python implementation for the above approach # Function to calculate longest substring# with odd or even elementsdef LongestOddEvenSubarray(A, N):         # Initializing dp    # Initializing dp with 1    dp = 1         # ans will store the final answer    ans = 1         # Traversing the array from index 1 to N - 1    for i in range(1, N):               # Checking both current and previous element        # is even or odd        if ((A[i] % 2 == 0 and A[i - 1] % 2 == 0) or (A[i] % 2 != 0 and A[i - 1] % 2 != 0)):                         # Updating dp with (previous dp value) + 1            dp = dp + 1                         # Storing max element so far to ans            ans = max(ans, dp)        else:            dp = 1                 # Returning the final answer    return ans # Driver code # InputA =  [2, 5, 7, 2, 4, 6, 8, 3 ]N = len(A) # Function callprint(LongestOddEvenSubarray(A, N)) # This code is contributed by shivani
// C# implementation for the above approachusing System; public class GFG{ // Function to calculate longest subString// with odd or even elementsstatic int longestOddEvenSubarray(int []A, int N){       // Initializing dp    int dp;     // Initializing dp with 1    dp = 1;     // ans will store the readonly answer    int ans = 1;     // Traversing the array from index 1 to N - 1    for (int i = 1; i < N; i++) {         // Checking both current and previous element        // is even or odd        if ((A[i] % 2 == 0 && A[i - 1] % 2 == 0)            || (A[i] % 2 != 0 && A[i - 1] % 2 != 0)) {             // Updating dp with (previous dp value) + 1            dp = dp + 1;             // Storing max element so far to ans            ans = Math.Max(ans, dp);        }        else            dp = 1;    }     // Returning the readonly answer    return ans;} // Driver codepublic static void Main(String[] args){       // Input    int []A = { 2, 5, 7, 2, 4, 6, 8, 3 };    int N = A.Length;     // Function call    Console.Write(longestOddEvenSubarray(A, N));}} // This code is contributed by shikhasingrajput
<script>// Javascript implementation for the above approach // Function to calculate longest substring// with odd or even elementsfunction LongestOddEvenSubarray(A, N) {  // Initializing dp  let dp;   // Initializing dp with 1  dp = 1;   // ans will store the final answer  let ans = 1;   // Traversing the array from index 1 to N - 1  for (let i = 1; i < N; i++) {    // Checking both current and previous element    // is even or odd    if (      (A[i] % 2 == 0 && A[i - 1] % 2 == 0) ||      (A[i] % 2 != 0 && A[i - 1] % 2 != 0)    ) {      // Updating dp with (previous dp value) + 1      dp = dp + 1;       // Storing max element so far to ans      ans = Math.max(ans, dp);    } else dp = 1;  }   // Returning the final answer  return ans;} // Driver code// Inputlet A = [2, 5, 7, 2, 4, 6, 8, 3];let N = A.length; // Function calldocument.write(LongestOddEvenSubarray(A, N)); </script>
4
Time Complexity: O(N)Auxiliary Space: O(1)
lokeshpotta20
gfgking
SURENDRA_GANGWAR
target_2
_saurabh_jaiswal
amit143katiyar
shikhasingrajput
shivanisinghss2110
subarray
Arrays
Dynamic Programming
Arrays
Dynamic Programming
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.