Find the maximum length of the prefix | Function to return the maximum length of the required prefix ; Array to store the frequency of each element of the array ; Iterating for all the elements ; Update the frequency of the current element i . e . v ; Sorted positive values from counts array ; If current prefix satisfies the given conditions ; Return the maximum length ; Driver code
function Maximum_Length ( a ) { let counts = new Array ( 11 ) ; counts . fill ( 0 ) ; let ans = 0 ; for ( let index = 0 ; index < a . length ; index ++ ) { counts [ a [ index ] ] += 1 ; let k = [ ] ; for ( let i = 0 ; i < counts . length ; i ++ ) { if ( counts [ i ] != 0 ) { k . push ( i ) ; } } k . sort ( function ( a , b ) { return a - b } ) ; if ( k . length == 1 || ( k [ 0 ] == k [ k . length - 2 ] && k [ k . length - 1 ] - k [ k . length - 2 ] == 1 ) || ( k [ 0 ] == 1 && k [ 1 ] == k [ k . length - 1 ] ) ) ans = index ; } return ( ans ) ; } let a = [ 1 , 1 , 1 , 2 , 2 , 2 ] ; document . write ( Maximum_Length ( a ) ) ;