Maximum length sub | Java implementation of the approach ; Function to return the maximum length of the required sub - array ; To store the maximum length for a valid subarray ; To store the count of contiguous similar elements for previous group and the current group ; If current element is equal to the previous element then it is a part of the same group ; Else update the previous group and start counting elements for the new group ; Update the maximum possible length for a group ; Return the maximum length of the valid subarray ; Driver code
class GFG { static int maxLength ( int a [ ] , int n ) { int maxLen = 0 ; int prev_cnt = 0 , curr_cnt = 1 ; for ( int i = 1 ; i < n ; i ++ ) { if ( a [ i ] == a [ i - 1 ] ) curr_cnt ++ ; else { prev_cnt = curr_cnt ; curr_cnt = 1 ; } maxLen = Math . max ( maxLen , Math . min ( prev_cnt , curr_cnt ) ) ; } return ( 2 * maxLen ) ; } public static void main ( String [ ] args ) { int arr [ ] = { 1 , 1 , 1 , 0 , 0 , 1 , 1 } ; int n = arr . length ; System . out . println ( maxLength ( arr , n ) ) ; } }