Maximum frequencies in each M | Java 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
import java . util . * ; class GFG { static void maxFrequencySubarrayUtil ( int [ ] A , int N , int M ) { int i = 0 ; HashMap < Integer , Integer > m = new HashMap < Integer , Integer > ( ) ; int val = 0 ; for ( ; i < M ; i ++ ) { if ( m . containsKey ( A [ i ] ) ) { m . put ( A [ i ] , m . get ( A [ i ] ) + 1 ) ; } else { m . put ( A [ i ] , 1 ) ; } val = Math . max ( val , m . get ( A [ i ] ) ) ; } System . out . print ( val + " ▁ " ) ; for ( i = M ; i < N ; i ++ ) { if ( m . containsKey ( i - M ) ) { m . put ( i - M , m . get ( i - M ) - 1 ) ; } if ( m . containsKey ( A [ i ] ) ) { m . put ( A [ i ] , m . get ( A [ i ] ) + 1 ) ; } else { m . put ( A [ i ] , 1 ) ; } val = 0 ; for ( Map . Entry < Integer , Integer > x : m . entrySet ( ) ) { val = Math . max ( val , x . getValue ( ) ) ; } System . out . print ( val + " ▁ " ) ; } } public static void main ( String [ ] args ) { int [ ] A = { 1 , 1 , 2 , 2 , 3 , 5 } ; int N = A . length ; int M = 4 ; maxFrequencySubarrayUtil ( A , N , M ) ; } }