Count of subarrays with X as the most frequent element , for each value of X from 1 to N | Java program for the above approach ; 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 ; Print answer ; Driver Code ; Input ; Function call
import java . util . * ; class GFG { public static void mostFrequent ( int [ ] arr , int N ) { int [ ] ans = new int [ N ] ; for ( int i = 0 ; i < N ; i ++ ) { int [ ] count = new int [ N ] ; int best = 1 ; for ( int j = i ; j < N ; j ++ ) { count [ arr [ j ] - 1 ] ++ ; if ( best > 0 ) { if ( ( count [ arr [ j ] - 1 ] > count [ best - 1 ] ) || ( count [ arr [ j ] - 1 ] == count [ best - 1 ] && arr [ j ] < best ) ) { best = arr [ j ] ; } ans [ best - 1 ] ++ ; } } } for ( int i = 0 ; i < N ; i ++ ) System . out . print ( ans [ i ] + " ▁ " ) ; } public static void main ( String [ ] args ) { int [ ] arr = { 2 , 1 , 2 , 3 } ; int N = arr . length ; mostFrequent ( arr , N ) ; } }