[LeetCode] Maximum Number of Balls in a Box

1742. Maximum Number of Balls in a Box

You are working in a ball factory where you have n balls numbered from lowLimit up to highLimit inclusive (i.e., n == highLimit - lowLimit + 1), and an infinite number of boxes numbered from 1 to infinity.

Your job at this factory is to put each ball in the box with a number equal to the sum of digits of the ball’s number. For example, the ball number 321 will be put in the box number 3 + 2 + 1 = 6 and the ball number 10 will be put in the box number 1 + 0 = 1.

Given two integers lowLimit and highLimit, return the number of balls in the box with the most balls.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class Solution {
int d(int x) {
int res = 0;
while(x) {
res += x % 10; x /= 10;
}
return res;
}
public:
int countBalls(int lowLimit, int highLimit) {
int res = 0;
vector<int> buc(55);
for(int i = lowLimit; i <= highLimit; i++) {
res = max(res, ++buc[d(i)]);
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2024/05/17/PS/LeetCode/maximum-number-of-balls-in-a-box/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.