Maximum frequencies in each M | C ++ program for the above approach ; Function to find the frequency of the most common element in each M length subarrays ; Stores frequency of array element ; Stores the maximum frequency ; Iterate for the first sub - array and store the maximum ; Print the maximum frequency for the first subarray ; Iterate over the range [ M , N ] ; Subtract the A [ i - M ] and add the A [ i ] in the map ; Find the maximum frequency ; Print the maximum frequency for the current subarray ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void maxFrequencySubarrayUtil ( vector < int > A , int N , int M ) { int i = 0 ; unordered_map < int , int > m ; int val = 0 ; for ( ; i < M ; i ++ ) { m [ A [ i ] ] ++ ; val = max ( val , m [ A [ i ] ] ) ; } cout << val << " ▁ " ; for ( i = M ; i < N ; i ++ ) { m [ A [ i - M ] ] -- ; m [ A [ i ] ] ++ ; val = 0 ; for ( auto x : m ) { val = max ( val , x . second ) ; } cout << val << " ▁ " ; } } int main ( ) { vector < int > A = { 1 , 1 , 2 , 2 , 3 , 5 } ; int N = A . size ( ) ; int M = 4 ; maxFrequencySubarrayUtil ( A , N , M ) ; return 0 ; }