Maximum Number of Balls in a Box
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
 class Solution:
def countBalls(self, lowLimit: int, highLimit: int) > int:
box_counts = {}
# generate all the balls
balls = list(range(lowLimit, highLimit+1))
# for each ball
for ball in balls:
# convert the ball number into a string
str_ball = str(ball)
# initialize the box number to 0
box = 0
# for each digit in the string representation of the ball number
for digit in str_ball:
# add the digit (converted back to an integer) to the box number
box += int(digit)
# if this box already has some balls
if box in box_counts:
# increment the count of balls in this box
box_counts[box] += 1
else:
# this box is encountered the first time, so initialize the count of balls in it to 1
box_counts[box] = 1
# after all balls have been put in their boxes, find the box with the maximum number of balls
max_balls = max(box_counts.values())
return max_balls

1
2
3
4
5
6
7
8
9
10
11
 class Solution:
def countBalls(self, lowLimit: int, highLimit: int) > int:
cnt = [0] * 46
for i in range(lowLimit, highLimit + 1):
n = i
_sum = 0
while n > 0:
_sum += n % 10
n //= 10
cnt[_sum] += 1
return max(cnt)

In this code, we first initialize a list cnt
of 46 zeros. Then we iterate over the range from lowLimit
to highLimit
inclusive. For each number i
in this range, we calculate the sum of its digits (_sum
). To get each digit of i
, we use the modulo operation (n % 10
), and then we do integer division by 10 (n //= 10
) to remove the last digit. After the sum of digits is calculated, we increment the corresponding element in the cnt
list. Finally, we return the maximum value from the cnt
list, which is the box with the most balls.