Maximum length sub | Function to return the maximum length of the required sub - array ; For the first consecutive pair of elements ; While a consecutive pair can be selected ; If current pair forms a valid sub - array ; 2 is the length of the current sub - array ; To extend the sub - array both ways ; While elements at indices l and r are part of a valid sub - array ; Update the maximum length so far ; Select the next consecutive pair ; Return the maximum length ; Driver code
def maxLength ( arr , n ) : NEW_LINE INDENT maxLen = 0 NEW_LINE i = 0 NEW_LINE j = i + 1 NEW_LINE while ( j < n ) : NEW_LINE INDENT if ( arr [ i ] != arr [ j ] ) : NEW_LINE INDENT maxLen = max ( maxLen , 2 ) NEW_LINE l = i - 1 NEW_LINE r = j + 1 NEW_LINE while ( l >= 0 and r < n and arr [ l ] == arr [ i ] and arr [ r ] == arr [ j ] ) : NEW_LINE INDENT l -= 1 NEW_LINE r += 1 NEW_LINE DEDENT maxLen = max ( maxLen , 2 * ( r - j ) ) NEW_LINE DEDENT i += 1 NEW_LINE j = i + 1 NEW_LINE DEDENT return maxLen NEW_LINE DEDENT arr = [ 1 , 1 , 1 , 0 , 0 , 1 , 1 ] NEW_LINE n = len ( arr ) NEW_LINE print ( maxLength ( arr , n ) ) NEW_LINE