Given two integers lowLimit
and highLimit
, you have a sequence of boxes numbered from 1 to infinity. Each box can contain balls, and you have one ball for every integer in the range [lowLimit, highLimit]
(inclusive). For each number i
in this range, you put a ball into the box with the number equal to the sum of the digits of i
. For example, if i = 321
, the sum of its digits is 3 + 2 + 1 = 6, so you put the ball into box 6.
Your task is to return the maximum number of balls in any box after all balls are distributed.
1 ≤ lowLimit ≤ highLimit ≤ 10^5
To solve this problem, let's break down the requirements:
lowLimit
and highLimit
, compute the sum of its digits.The problem can be solved efficiently with the following steps:
i
from lowLimit
to highLimit
(inclusive), compute the sum of its digits.We use a hash map (or array) because it allows for quick lookups and updates. The digit sum calculation is straightforward and can be done in a helper function.
Let's use lowLimit = 1
and highLimit = 10
as an example.
Brute-force Approach:
highLimit - lowLimit + 1
and D is the maximum number of digits (at most 5). For each number, we must sum its digits.
The key to solving the "Maximum Number of Balls in a Box" problem is recognizing that the sum of the digits uniquely identifies the box for each ball. By counting how many times each digit sum occurs, we can efficiently determine the box with the most balls. The solution leverages simple iteration, digit sum calculation, and a hash map (or array) for counting, making it both intuitive and efficient.
class Solution:
def countBalls(self, lowLimit: int, highLimit: int) -> int:
from collections import defaultdict
box_counts = defaultdict(int)
for i in range(lowLimit, highLimit + 1):
digit_sum = 0
n = i
while n > 0:
digit_sum += n % 10
n //= 10
box_counts[digit_sum] += 1
return max(box_counts.values())
class Solution {
public:
int countBalls(int lowLimit, int highLimit) {
unordered_map<int, int> boxCounts;
for (int i = lowLimit; i <= highLimit; ++i) {
int n = i, digitSum = 0;
while (n > 0) {
digitSum += n % 10;
n /= 10;
}
boxCounts[digitSum]++;
}
int maxBalls = 0;
for (auto &entry : boxCounts) {
if (entry.second > maxBalls) {
maxBalls = entry.second;
}
}
return maxBalls;
}
};
class Solution {
public int countBalls(int lowLimit, int highLimit) {
Map<Integer, Integer> boxCounts = new HashMap<>();
for (int i = lowLimit; i <= highLimit; i++) {
int n = i, digitSum = 0;
while (n > 0) {
digitSum += n % 10;
n /= 10;
}
boxCounts.put(digitSum, boxCounts.getOrDefault(digitSum, 0) + 1);
}
int maxBalls = 0;
for (int count : boxCounts.values()) {
maxBalls = Math.max(maxBalls, count);
}
return maxBalls;
}
}
var countBalls = function(lowLimit, highLimit) {
const boxCounts = {};
for (let i = lowLimit; i <= highLimit; i++) {
let n = i, digitSum = 0;
while (n > 0) {
digitSum += n % 10;
n = Math.floor(n / 10);
}
boxCounts[digitSum] = (boxCounts[digitSum] || 0) + 1;
}
return Math.max(...Object.values(boxCounts));
};