Skip to content

1399. Count Largest Group 👎

  • Time: $O(n\log n)$
  • Space: $O(n)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
class Solution {
 public:
  int countLargestGroup(int n) {
    vector<int> count(9 * 4 + 1);
    for (int i = 1; i <= n; ++i)
      ++count[getDigitSum(i)];
    return ranges::count(count, ranges::max(count));
  }

 private:
  int getDigitSum(int num) {
    int digitSum = 0;
    while (num > 0) {
      digitSum += num % 10;
      num /= 10;
    }
    return digitSum;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
class Solution {
  public int countLargestGroup(int n) {
    int[] count = new int[9 * 4 + 1];
    for (int i = 1; i <= n; ++i)
      ++count[getDigitSum(i)];
    final int mx = Arrays.stream(count).max().getAsInt();
    return (int) Arrays.stream(count).filter(c -> c == mx).count();
  }

  private int getDigitSum(int num) {
    int digitSum = 0;
    while (num > 0) {
      digitSum += num % 10;
      num /= 10;
    }
    return digitSum;
  }
}
1
2
3
4
5
6
7
8
9
class Solution:
  def countLargestGroup(self, n: int) -> int:
    count = [0] * (9 * 4 + 1)
    for i in range(1, n + 1):
      count[self._getDigitSum(i)] += 1
    return count.count(max(count))

  def _getDigitSum(self, num: int) -> int:
    return sum(int(digit) for digit in str(num))