You are working in a ball factory where you have n balls numbered from
lowLimit up to highLimitinclusive (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.
Input: lowLimit =1, highLimit =10Output: 2Explanation:
Box Number:1234567891011...Ball Count:21111111100...Box 1 has the most number of balls with2 balls.
Input: lowLimit =5, highLimit =15Output: 2Explanation:
Box Number:1234567891011...Ball Count:11112211100...Boxes 5 and 6 have the most number of balls with2 balls in each.
Input: lowLimit =19, highLimit =28Output: 2Explanation:
Box Number:123456789101112...Ball Count:011111111200...Box 10 has the most number of balls with2 balls.
Each ball is placed in a box whose number is the sum of the digits of the ball’s number. We count how many balls go into each box and return the maximum count.
classSolution {
public:int countBalls(int lowLimit, int highLimit) {
unordered_map<int, int> cnt;
int ans =0;
for (int i = lowLimit; i <= highLimit; ++i) {
int s =0, x = i;
while (x) {
s += x %10;
x /=10;
}
ans = max(ans, ++cnt[s]);
}
return ans;
}
};
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
funccountBalls(lowLimitint, highLimitint) int {
cnt:= make(map[int]int)
ans:=0fori:=lowLimit; i<=highLimit; i++ {
s, x:=0, iforx > 0 {
s+=x%10x/=10 }
cnt[s]++ifcnt[s] > ans {
ans = cnt[s]
}
}
returnans}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
classSolution {
publicintcountBalls(int lowLimit, int highLimit) {
Map<Integer, Integer> cnt =new HashMap<>();
int ans = 0;
for (int i = lowLimit; i <= highLimit; i++) {
int s = 0, x = i;
while (x > 0) {
s += x % 10;
x /= 10;
}
cnt.put(s, cnt.getOrDefault(s, 0) + 1);
ans = Math.max(ans, cnt.get(s));
}
return ans;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
classSolution {
funcountBalls(lowLimit: Int, highLimit: Int): Int {
val cnt = mutableMapOf<Int, Int>()
var ans = 0for (i in lowLimit..highLimit) {
var s = 0var x = i
while (x > 0) {
s += x % 10 x /=10 }
cnt[s] = cnt.getOrDefault(s, 0) + 1 ans = maxOf(ans, cnt[s]!!)
}
return ans
}
}
1
2
3
4
5
6
7
8
9
classSolution:
defcountBalls(self, lowLimit: int, highLimit: int) -> int:
cnt: dict[int, int] = {}
ans =0for i in range(lowLimit, highLimit +1):
s = sum(int(d) for d in str(i))
cnt[s] = cnt.get(s, 0) +1 ans = max(ans, cnt[s])
return ans
impl Solution {
pubfncount_balls(low_limit: i32, high_limit: i32) -> i32 {
use std::collections::HashMap;
letmut cnt = HashMap::new();
letmut ans =0;
for i in low_limit..=high_limit {
letmut s =0;
letmut x = i;
while x >0 {
s += x %10;
x /=10;
}
let c = cnt.entry(s).or_insert(0);
*c +=1;
if*c > ans {
ans =*c;
}
}
ans
}
}