2025-04-23 Daily Challenge

Today I have done leetcode's April LeetCoding Challenge with cpp.

April LeetCoding Challenge 23

Description

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.

 

Example 1:

Input: n = 13
Output: 4
Explanation: 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:

Input: n = 2
Output: 2
Explanation: There are 2 groups [1], [2] of size 1.

 

Constraints:

  • 1 <= n <= 104

Solution

class Solution {
public:
  int countLargestGroup(int n) {
    map<int, int> count;
    for(int i = 1; i <= n; ++i) {
      int sum = 0;
      int current = i;
      while(current) {
        sum += current % 10;
        current /= 10;
      }
      count[sum] += 1;
    }
    int answer = 0;
    int size = 0;
    for(const auto &[_s, c] : count) {
      if(c > size) {
        answer = 0;
        size = c;
      }
      answer += (c == size);
    }
    return answer;
  }
};

// Accepted
// 75/75 cases passed (3 ms)
// Your runtime beats 33.9 % of cpp submissions
// Your memory usage beats 74.92 % of cpp submissions (8 MB)