text: Find the maximum length of the prefix | Java implementation of the approach ; 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
code: import java . util . * ; public class Main { public static int Maximum_Length ( Vector < Integer > a ) { int [ ] counts = new int [ 11 ] ; int ans = 0 ; for ( int index = 0 ; index < a . size ( ) ; index ++ ) { counts [ a . get ( index ) ] += 1 ; Vector < Integer > k = new Vector < Integer > ( ) ; for ( int i : counts ) if ( i != 0 ) k . add ( i ) ; Collections . sort ( k ) ; if ( k . size ( ) == 1 || ( k . get ( 0 ) == k . get ( k . size ( ) - 2 ) && k . get ( k . size ( ) - 1 ) - k . get ( k . size ( ) - 2 ) == 1 ) || ( k . get ( 0 ) == 1 && k . get ( 1 ) == k . get ( k . size ( ) - 1 ) ) ) ans = index ; } return ans + 1 ; } public static void main ( String [ ] args ) { Vector < Integer > a = new Vector < Integer > ( ) ; a . add ( 1 ) ; a . add ( 1 ) ; a . add ( 1 ) ; a . add ( 2 ) ; a . add ( 2 ) ; a . add ( 2 ) ; System . out . println ( Maximum_Length ( a ) ) ; } }