[LeetCode] Count Largest Group

1399. Count Largest Group

You are given an integer n.

Each number from 1 to n is grouped according to the sum of its digits.

Return the number of groups that have the largest size.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class Solution {
int sum(int n) {
int res = 0;
while(n) {
res += n % 10;
n /= 10;
}
return res;
}
public:
int countLargestGroup(int n) {
unordered_map<int,int> mp;
int ma = 0;
for(int i = 1; i <= n; i++) ma = max(ma, ++mp[sum(i)]);
int res = 0;
for(auto& [k,v] : mp) res += v == ma;
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2025/04/23/PS/LeetCode/count-largest-group/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.