Skip to content

Instantly share code, notes, and snippets.

@JyotinderSingh
Created July 7, 2020 05:56
Show Gist options
  • Save JyotinderSingh/0f8ca3978eff68704f334a2d4baa18ab to your computer and use it in GitHub Desktop.
Save JyotinderSingh/0f8ca3978eff68704f334a2d4baa18ab to your computer and use it in GitHub Desktop.
Count Largest Group (LeetCode) | Interview Question Explanation
class Solution
{
public:
int countLargestGroup(int n)
{
// vector to maintain sizes of each of the groups
// note that max sum of digits can be for 9999 (9 + 9 + 9 + 9 = 36)
vector<int> count(37);
int max_size = 0;
int res = 0;
for (int i = 1; i <= n; ++i)
{
max_size = max(max_size, ++count[digSum(i)]);
}
for (int i = 0; i < count.size(); ++i)
{
if (count[i] == max_size)
res++;
}
return res;
}
int digSum(int n)
{
int sum = 0;
while (n)
{
sum += n % 10;
n /= 10;
}
return sum;
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment