1742. 盒子中小球的最大数量 - 力扣(LeetCode)



这是一个典型的“桶统计”类问题。我们可以通过以下步骤解决它:
步骤:
-
遍历从
lowLimit到highLimit的每个小球编号。 -
计算每个编号的数位和,作为盒子的编号。
-
使用一个字典或数组来记录每个盒子中小球的数量。
-
最后返回盒子中小球数量的最大值。
Python 实现:
def countBalls(lowLimit: int, highLimit: int) -> int:
from collections import defaultdict
box_counts = defaultdict(int)
for num in range(lowLimit, highLimit + 1):
# 计算数位和
digit_sum = sum(int(d) for d in str(num))
box_counts[digit_sum] += 1
return max(box_counts.values())
示例:
如果 lowLimit = 1,highLimit = 10,每个小球的盒子如下:
-
1 → 1
-
2 → 2
-
3 → 3
-
...
-
10 → 1
那么盒子编号 1 有两个小球(1 和 10),其他最多有一个,所以返回 2。
303

被折叠的 条评论
为什么被折叠?



