forked from anishLearnsToCode/leetcode-algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
/
CountLargestGroup.java
36 lines (33 loc) · 1.17 KB
/
CountLargestGroup.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
import java.util.HashMap;
import java.util.Map;
public class CountLargestGroup {
public int countLargestGroup(int n) {
Map<Integer, Integer> sumOfDigitsFrequencies = getFrequenciesOfSumOfDigits(n);
int largestGroupSize = 0, largestGroupFrequency = 0;
for (int groupSize : sumOfDigitsFrequencies.values()) {
if (groupSize > largestGroupSize) {
largestGroupSize = groupSize;
largestGroupFrequency = 1;
} else if (largestGroupSize == groupSize) {
largestGroupFrequency++;
}
}
return largestGroupFrequency;
}
private Map<Integer, Integer> getFrequenciesOfSumOfDigits(int N) {
Map<Integer, Integer> frequencies = new HashMap<>();
for (int number = 1 ; number <= N ; number++) {
int sumOfDigits = sumOfDigits(number);
frequencies.put(sumOfDigits, frequencies.getOrDefault(sumOfDigits, 0) + 1);
}
return frequencies;
}
private int sumOfDigits(int number) {
int sum = 0;
while (number > 0) {
sum += number % 10;
number /= 10;
}
return sum;
}
}