Count of groups having largest size while grouping according to sum of its digits | Java implementation to Count the number of groups having the largest size where groups are according to the sum of its digits ; Function to return sum of digits of i ; Create the dictionary of unique sum ; dictionary that contain unique sum count ; Calculate the sum of its digits ; Function to find the largest size of group ; Count of largest size group ; Driver code
import java . util . HashMap ; import java . util . Map ; class GFG { public static int sumDigits ( int n ) { int sum = 0 ; while ( n != 0 ) { sum += n % 10 ; n /= 10 ; } return sum ; } public static HashMap < Integer , Integer > constDict ( int n ) { HashMap < Integer , Integer > d = new HashMap < > ( ) ; for ( int i = 1 ; i < n + 1 ; ++ i ) { int sum1 = sumDigits ( i ) ; if ( ! d . containsKey ( sum1 ) ) d . put ( sum1 , 1 ) ; else d . put ( sum1 , d . get ( sum1 ) + 1 ) ; } return d ; } public static int countLargest ( int n ) { HashMap < Integer , Integer > d = constDict ( n ) ; int size = 0 ; int count = 0 ; for ( Map . Entry < Integer , Integer > it : d . entrySet ( ) ) { int k = it . getKey ( ) ; int val = it . getValue ( ) ; if ( val > size ) { size = val ; count = 1 ; } else if ( val == size ) count += 1 ; } return count ; } public static void main ( String [ ] args ) { int n = 13 ; int group = countLargest ( n ) ; System . out . println ( group ) ; } }