Input: n =13Output: 4Explanation: There are 9 groups in total, they are grouped according sum of its digits of numbers from 1 to 13:[1,10],[2,11],[3,12],[4,13],[5],[6],[7],[8],[9].There are 4 groups with largest size.
Example 2:
1
2
3
Input: n =2Output: 2Explanation: There are 2 groups [1],[2] of size 1.
classSolution {
publicintcountLargestGroup(int n) {
HashMap<Integer, Integer> count =new HashMap<>();
// Count group sizes by digit sumfor (int i = 1; i <= n; i++) {
int s = digitSum(i);
count.put(s, count.getOrDefault(s, 0) + 1);
}
// Find the largest group sizeint maxSize = 0;
for (int size : count.values()) {
maxSize = Math.max(maxSize, size);
}
// Count groups of the largest sizeint ans = 0;
for (int size : count.values()) {
if (size == maxSize) {
ans++;
}
}
return ans;
}
// Helper function to calculate sum of digitsprivateintdigitSum(int x) {
int total = 0;
while (x > 0) {
total += x % 10;
x /= 10;
}
return total;
}
}
classSolution:
defcountLargestGroup(self, n: int) -> int:
count: defaultdict[int, int] = defaultdict(int)
# Helper to calculate digit sumdefdigit_sum(x: int) -> int:
total =0while x >0:
total += x %10 x //=10return total
# Count group sizes by digit sumfor i in range(1, n +1):
s = digit_sum(i)
count[s] +=1# Find the largest group size max_size = max(count.values())
# Count groups of the largest size ans = sum(1for group in count.values() if group == max_size)
return ans