Count of subarrays with X as the most frequent element , for each value of X from 1 to N | Function to calculate the number of subarrays where X ( 1 <= X <= N ) is the most frequent element ; array to store the final answers ; Array to store current frequencies ; Variable to store the current most frequent element ; Update frequency array ; Update answer ; Pranswer ; Driver code ; Input ; Function call
def mostFrequent ( arr , N ) : NEW_LINE INDENT ans = [ 0 ] * N NEW_LINE for i in range ( N ) : NEW_LINE INDENT count = [ 0 ] * N NEW_LINE best = 0 NEW_LINE for j in range ( i , N ) : NEW_LINE INDENT count [ arr [ j ] - 1 ] += 1 NEW_LINE if ( count [ arr [ j ] - 1 ] > count [ best - 1 ] or ( count [ arr [ j ] - 1 ] == count [ best - 1 ] and arr [ j ] < best ) ) : NEW_LINE INDENT best = arr [ j ] NEW_LINE DEDENT ans [ best - 1 ] += 1 NEW_LINE DEDENT DEDENT print ( * ans ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 2 , 1 , 2 , 3 ] NEW_LINE N = len ( arr ) NEW_LINE mostFrequent ( arr , N ) NEW_LINE DEDENT