# Program to find maximum number of balls in a box using Python

PythonServer Side ProgrammingProgramming

Suppose we have a ball factory where we have n balls numbered from l to r (both inclusive) and have an infinite number of boxes numbered from 1 to infinity. So if we put each ball in the box with a number same to the sum of digits of the ball's number. (As an example, the ball number 123 will be put in the box number 1 + 2 + 3 = 6). So if we have two values l and r, we have to find the number of balls in the box with the most balls.

So, if the input is like l = 15 r = 25, then the output will be 2 because

• The ball number 15 will be put inside 1+5 = 6

• The ball number 16 will be put inside 1+6 = 7

• The ball number 17 will be put inside 1+7 = 8

• The ball number 18 will be put inside 1+8 = 9

• The ball number 19 will be put inside 1+9 = 10

• The ball number 20 will be put inside 2+0 = 2

• The ball number 21 will be put inside 2+1 = 3

• The ball number 22 will be put inside 2+2 = 4

• The ball number 23 will be put inside 2+3 = 5

• The ball number 24 will be put inside 2+4 = 6

• The ball number 25 will be put inside 2+5 = 7

so box 6 and 7 contains maximum number of balls, that's why answer is 2

To solve this, we will follow these steps −

• dict:= a new map

• for i in range l to r, do

• total:= 0

• for each digit j of i, do

• total := total + j

• if total is not present in dict, then

• dict[total] := 0

• dict[total] := dict[total] + 1

• return maximum of all values for all keys in dict

## Example (Python)

Let us see the following implementation to get better understanding −

Live Demo

def solve(l, r):
dict={}
for i in range(l, r+1):
total=0
for j in str(i):
total += int(j)
if(total not in dict):
dict[total] = 0
dict[total] += 1
return max([dict[i] for i in dict])

l = 15
r = 25
print(solve(l, r))

## Input

15, 25

## Output

1
Updated on 18-May-2021 11:56:18