Maximum Number of Balls in a Box - Problem

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.

Input & Output

Example 1 — Small Range
$ Input: lowLimit = 1, highLimit = 10
Output: 2
💡 Note: Balls 1,10 both go to box 1 (digit sum 1). Balls 2-9 each go to different boxes. Box 1 has maximum 2 balls.
Example 2 — Sequential Range
$ Input: lowLimit = 5, highLimit = 15
Output: 2
💡 Note: Balls 5,14 both go to box 5 (5+0=5, 1+4=5). Ball 6→box6, 7→box7, etc. Box 5 has maximum 2 balls.
Example 3 — Same Digit Sum
$ Input: lowLimit = 19, highLimit = 28
Output: 2
💡 Note: Balls 19,28 both go to box 10 (1+9=10, 2+8=10). Most other balls go to unique boxes.

Constraints

  • 1 ≤ lowLimit ≤ highLimit ≤ 105

Visualization

Tap to expand
Maximum Number of Balls in a Box INPUT Balls numbered 1 to 10 1 2 3 4 5 6 7 8 9 10 lowLimit = 1 highLimit = 10 n = 10 balls total Digit Sum Examples: Ball 5 --> Box 5 Ball 10 --> Box 1+0=1 Ball 321 --> Box 3+2+1=6 ALGORITHM STEPS 1 Initialize Array boxes[46] = {0} for counts 2 Loop: low to high For each ball number 3 Calculate Digit Sum sum = sum of all digits 4 Update Box Count boxes[sum]++ and track max Box Distribution: Box: 1 2 3 4 5 ... Cnt: 2 1 1 1 1 ... Box 1: balls 1, 10 (count=2) Box 2-9: ball 2-9 (count=1 each) FINAL RESULT Box with Most Balls: BOX 1 1 10 Ball 1: digit sum = 1 Ball 10: 1+0 = 1 Both go to Box 1! OUTPUT 2 OK - Maximum count Box 1 has 2 balls Key Insight: Use an array to count balls per box. Max digit sum for numbers up to 10^5 is 9*5=45, so array size 46 is enough. Single pass O(n * log10(highLimit)) time, O(1) space. Extract digits using modulo and division operations. TutorialsPoint - Maximum Number of Balls in a Box | Single Pass with Array Approach
Asked in
Amazon 15 Google 12
25.0K Views
Medium Frequency
~15 min Avg. Time
450 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen