# 1742. Maximum Number of Balls in a Box¶

• Time:
• Space:
  1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 class Solution { public: int countBalls(int lowLimit, int highLimit) { const int maxDigitSum = 9 * 5; // 99999 int ans = 0; vector count(maxDigitSum + 1); for (int num = lowLimit; num <= highLimit; ++num) ans = max(ans, ++count[getDigitSum(num)]); return ans; } 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 19 20 21 class Solution { public int countBalls(int lowLimit, int highLimit) { final int maxDigitSum = 9 * 5; // 99999 int ans = 0; int[] count = new int[maxDigitSum + 1]; for (int num = lowLimit; num <= highLimit; ++num) ans = Math.max(ans, ++count[getDigitSum(num)]); return ans; } 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 class Solution: def countBalls(self, lowLimit: int, highLimit: int) -> int: maxDigitSum = 9 * 5 # 99999 ans = 0 count = [0] * (maxDigitSum + 1) for num in range(lowLimit, highLimit + 1): digitSum = self._getDigitSum(num) count[digitSum] += 1 ans = max(ans, count[digitSum]) return ans def _getDigitSum(self, num: int) -> int: return sum(int(digit) for digit in str(num))