Count of subarrays with X as the most frequent element , for each value of X from 1 to N | C ++ 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 ; Initialise count ; Variable to store the current most frequent element ; Update frequency array ; Update answer ; Print answer ; Driver code ; Input ; Function call
#include <bits/stdc++.h> NEW_LINE using namespace std ; int mostFrequent ( int arr [ ] , int N ) { int ans [ N ] = { 0 } ; for ( int i = 0 ; i < N ; i ++ ) { int count [ N ] ; memset ( count , 0 , sizeof ( count ) ) ; int best = 0 ; for ( int 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 ] ++ ; } } for ( int i = 0 ; i < N ; i ++ ) cout << ans [ i ] << " ▁ " ; } int main ( ) { int arr [ ] = { 2 , 1 , 2 , 3 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; mostFrequent ( arr , N ) ; return 0 ; }