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
function maxFrequencySubarrayUtil ( A , N , M ) { let m = new Map ( ) ; let val = 0 ; for ( let i = 0 ; i < M ; i ++ ) { if ( m . has ( A [ i ] ) ) { m . set ( m . get ( A [ i ] ) , m . get ( A [ i ] ) + 1 ) ; } else { m . set ( A [ i ] , 1 ) ; } val = Math . max ( val , m . get ( A [ i ] ) ) ; } document . write ( val + " " ) ; for ( i = M ; i < N ; i ++ ) { if ( m . has ( A [ i - m ] ) ) m . set ( m . get ( A [ i - M ] ) , m . get ( A [ i - M ] ) - 1 ) ; if ( m . has ( A [ i ] ) ) m . set ( m . get ( A [ i ] ) , m . get ( A [ i ] ) + 1 ) ; val = 0 ; for ( let [ key , value ] of m ) { val = Math . max ( val , value ) ; } document . write ( val + " " ) ; } } let A = [ 1 , 1 , 2 , 2 , 3 , 5 ] ; let N = A . length ; let M = 4 ; maxFrequencySubarrayUtil ( A , N , M ) ;