text: Find the maximum length of the prefix | C ++ 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: #include <bits/stdc++.h> NEW_LINE using namespace std ; int Maximum_Length ( vector < int > a ) { int counts [ 11 ] = { 0 } ; int ans = 0 ; for ( int index = 0 ; index < a . size ( ) ; index ++ ) { counts [ a [ index ] ] += 1 ; vector < int > k ; for ( auto i : counts ) if ( i != 0 ) k . push_back ( i ) ; sort ( k . begin ( ) , k . end ( ) ) ; if ( k . size ( ) == 1 || ( k [ 0 ] == k [ k . size ( ) - 2 ] && k . back ( ) - k [ k . size ( ) - 2 ] == 1 ) || ( k [ 0 ] == 1 and k [ 1 ] == k . back ( ) ) ) ans = index ; } return ans + 1 ; } int main ( ) { vector < int > a = { 1 , 1 , 1 , 2 , 2 , 2 } ; cout << ( Maximum_Length ( a ) ) ; }