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
function maxLength ( arr , n ) { let maxLen = 0 ; let i = 0 ; let j = i + 1 ; while ( j < n ) { if ( arr [ i ] != arr [ j ] ) { maxLen = Math . max ( maxLen , 2 ) ; let l = i - 1 ; let r = j + 1 ; while ( l >= 0 && r < n && arr [ l ] == arr [ i ] && arr [ r ] == arr [ j ] ) { l -- ; r ++ ; } maxLen = Math . max ( maxLen , 2 * ( r - j ) ) ; } i ++ ; j = i + 1 ; } return maxLen ; } let arr = [ 1 , 1 , 1 , 0 , 0 , 1 , 1 ] ; let n = arr . length ; document . write ( maxLength ( arr , n ) ) ;