1399: Count-Largest-Group
Easy
table of contents
Simple brute-force all solutions with a hash-map solution.
You can just iterate through all the digits between 1
and n and manually iterate through the hash-map to find the
number of groups with the largest size.
code
class Solution {
public:
unordered_map<int, int> mp;
int countLargestGroup(int n) {
for (int i = 1; i <= n; ++i) {
int copy = i;
int counter = 0;
while(copy > 0) {
counter += (copy % 10);
copy /= 10;
}
++mp[counter];
}
int ans = 0, mx = 0;
for (auto &[key, value] : mp) {
if (value > mx) {
ans = 1;
mx = value;
} else if (value == mx) {
++ans;
}
}
return ans;
}
};