Skip to main content
Back to problems
#1742
Easy Algorithms

Maximum number of balls in a box

Hash Table Math Counting
74.7% acceptance
Feb 25, 2026
653
170
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. Given two integers lowLimit and highLimit, return the number of balls in the box with the most balls.

Solution

Rust
Time O(n)
Space O(n)
LeetCode
solution.rs
impl Solution {
  pub fn count_balls(low_limit: i32, high_limit: i32) -> i32 {
    let digit_sum = |mut n: i32| -> usize {
      let mut s = 0;
      while n > 0 { s += (n % 10) as usize; n /= 10; }
      s
    };
    // Max digit sum for any number <= 10^5 is 9*5 = 45
    let mut boxes = vec![0i32; 46];
    for n in low_limit..=high_limit {
      boxes[digit_sum(n)] += 1;
    }
    *boxes.iter().max().unwrap()
  }
}