Created
July 7, 2020 05:56
-
-
Save JyotinderSingh/0f8ca3978eff68704f334a2d4baa18ab to your computer and use it in GitHub Desktop.
Count Largest Group (LeetCode) | Interview Question Explanation
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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