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 ; Initialise count ; Variable to store the current most frequent element ; Update frequency array ; Update answer ; Print answer ; Input ; Function call
function mostFrequent ( arr , N ) { let ans = new Array ( N ) . fill ( 0 ) for ( let i = 0 ; i < N ; i ++ ) { let count = new Array ( N ) ; count . fill ( 0 ) let best = 1 ; for ( let j = i ; j < N ; j ++ ) { count [ arr [ j ] - 1 ] ++ ; if ( count [ arr [ j ] - 1 ] > count [ best - 1 ] || ( count [ arr [ j ] - 1 ] == count [ best - 1 ] && arr [ j ] < best ) ) { best = arr [ j ] ; } ans [ best - 1 ] ++ ; } } console . log ( ans ) for ( let i = 0 ; i < N ; i ++ ) document . write ( ans [ i ] + " " ) ; } let arr = [ 2 , 1 , 2 , 3 ] ; let N = arr . length mostFrequent ( arr , N ) ;