Longest subarray with all even or all odd elements | C ++ implementation for the above approach ; Function to calculate longest substring with odd or even elements ; Initializing dp [ ] ; Initializing dp [ 0 ] with 1 ; ans will store the final answer ; Traversing the array from index 1 to N - 1 ; Checking both current and previous element is even or odd ; Updating dp [ i ] with dp [ i - 1 ] + 1 ; Storing max element to ans ; Returning the final answer ; Driver Code ; Input ; Function call
#include <bits/stdc++.h> NEW_LINE using namespace std ; int LongestOddEvenSubarray ( int A [ ] , int N ) { int dp [ N ] ; dp [ 0 ] = 1 ; int ans = 1 ; for ( int i = 1 ; i < N ; i ++ ) { if ( ( A [ i ] % 2 == 0 && A [ i - 1 ] % 2 == 0 ) || ( A [ i ] % 2 != 0 && A [ i - 1 ] % 2 != 0 ) ) { dp [ i ] = dp [ i - 1 ] + 1 ; } else dp [ i ] = 1 ; } for ( int i = 0 ; i < N ; i ++ ) ans = max ( ans , dp [ i ] ) ; return ans ; } int main ( ) { int A [ ] = { 2 , 5 , 7 , 2 , 4 , 6 , 8 , 3 } ; int N = sizeof ( A ) / sizeof ( A [ 0 ] ) ; cout << LongestOddEvenSubarray ( A , N ) ; return 0 ; }