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
def Maximum_Length ( a ) : NEW_LINE INDENT counts = [ 0 ] * 11 NEW_LINE for index , v in enumerate ( a ) : NEW_LINE INDENT counts [ v ] += 1 NEW_LINE k = sorted ( [ i for i in counts if i ] ) NEW_LINE if len ( k ) == 1 or ( k [ 0 ] == k [ - 2 ] and k [ - 1 ] - k [ - 2 ] == 1 ) or ( k [ 0 ] == 1 and k [ 1 ] == k [ - 1 ] ) : NEW_LINE INDENT ans = index NEW_LINE DEDENT DEDENT return ans + 1 NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT a = [ 1 , 1 , 1 , 2 , 2 , 2 ] NEW_LINE n = len ( a ) NEW_LINE print ( Maximum_Length ( a ) ) NEW_LINE DEDENT