text: Maximum length of subarray consisting of same type of element on both halves of sub | C ++ program for the above approach ; Function that finds the maximum length of the sub - array that contains equal element on both halves of sub - array ; To store continuous occurence of the element ; To store continuous forward occurence ; To store continuous backward occurence ; To store the maximum length ; Find maximum length ; Print the result ; Driver Code ; Given array ; Size of the array ; Function Call
code: #include <bits/stdc++.h> NEW_LINE using namespace std ; void maxLengthSubArray ( int A [ ] , int N ) { int forward [ N ] , backward [ N ] ; for ( int i = 0 ; i < N ; i ++ ) { if ( i == 0 A [ i ] != A [ i - 1 ] ) { forward [ i ] = 1 ; } else forward [ i ] = forward [ i - 1 ] + 1 ; } for ( int i = N - 1 ; i >= 0 ; i -- ) { if ( i == N - 1 A [ i ] != A [ i + 1 ] ) { backward [ i ] = 1 ; } else backward [ i ] = backward [ i + 1 ] + 1 ; } int ans = 0 ; for ( int i = 0 ; i < N - 1 ; i ++ ) { if ( A [ i ] != A [ i + 1 ] ) ans = max ( ans , min ( forward [ i ] , backward [ i + 1 ] ) * 2 ) ; } cout << ans ; } int main ( ) { int arr [ ] = { 1 , 2 , 3 , 4 , 4 , 4 , 6 , 6 , 6 , 9 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; maxLengthSubArray ( arr , N ) ; return 0 ; }