Maximum frequencies in each M | 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
using System ; using System . Collections . Generic ; public class GFG { static void maxFrequencySubarrayUtil ( int [ ] A , int N , int M ) { int i = 0 ; Dictionary < int , int > m = new Dictionary < int , int > ( ) ; int val = 0 ; for ( ; i < M ; i ++ ) { if ( m . ContainsKey ( A [ i ] ) ) { val = m [ A [ i ] ] ; m . Remove ( A [ i ] ) ; m . Add ( A [ i ] , val + 1 ) ; } else { m . Add ( A [ i ] , 1 ) ; } val = Math . Max ( val , m [ A [ i ] ] ) ; } Console . Write ( val + " ▁ " ) ; for ( i = M ; i < N ; i ++ ) { if ( m . ContainsKey ( i - M ) ) { val = i - M ; m . Remove ( i - M ) ; m . Add ( i - M , val - 1 ) ; } if ( m . ContainsKey ( A [ i ] ) ) { val = m [ A [ i ] ] ; m . Remove ( A [ i ] ) ; m . Add ( A [ i ] , val + 1 ) ; } else { m . Add ( A [ i ] , 1 ) ; } val = Math . Max ( val , m [ A [ i ] ] ) ; val = 0 ; foreach ( KeyValuePair < int , int > x in m ) { val = Math . Max ( val , x . Value ) ; } Console . Write ( val + " ▁ " ) ; } } static public void Main ( ) { int [ ] A = { 1 , 1 , 2 , 2 , 3 , 5 } ; int N = 6 ; int M = 4 ; maxFrequencySubarrayUtil ( A , N , M ) ; } }