Difference between highest and least frequencies in an array | Java code to find the difference between highest and least frequencies ; Put all elements in a hash map ; Find counts of maximum and minimum frequent elements ; Driver code
import java . util . * ; class GFG { static int findDiff ( int arr [ ] , int n ) { Map < Integer , Integer > mp = new HashMap < > ( ) ; for ( int i = 0 ; i < n ; i ++ ) { if ( mp . containsKey ( arr [ i ] ) ) { mp . put ( arr [ i ] , mp . get ( arr [ i ] ) + 1 ) ; } else { mp . put ( arr [ i ] , 1 ) ; } } int max_count = 0 , min_count = n ; for ( Map . Entry < Integer , Integer > x : mp . entrySet ( ) ) { max_count = Math . max ( max_count , x . getValue ( ) ) ; min_count = Math . min ( min_count , x . getValue ( ) ) ; } return ( max_count - min_count ) ; } public static void main ( String [ ] args ) { int arr [ ] = { 7 , 8 , 4 , 5 , 4 , 1 , 1 , 7 , 7 , 2 , 5 } ; int n = arr . length ; System . out . println ( findDiff ( arr , n ) ) ; } }