https://leetcode.com/problems/maximum-number-of-balls-in-a-box/
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.
lowLimit <= 공의숫자 <= highLimit123 이면 1 + 2 + 3 = 6, 즉 6번 박스에 들어감Example 1:
Output: 2 Explanation: Box Number: 1 2 3 4 5 6 7 8 9 10 11 ... Ball Count: 2 1 1 1 1 1 1 1 1 0 0 ... Box 1 has the most number of balls with 2 balls.
Example 2:
Output: 2 Explanation: Box Number: 1 2 3 4 5 6 7 8 9 10 11 ... Ball Count: 1 1 1 1 2 2 1 1 1 0 0 ... Boxes 5 and 6 have the most number of balls with 2 balls in each.
Example 3:
Output: 2 Explanation: Box Number: 1 2 3 4 5 6 7 8 9 10 11 12 ... Ball Count: 0 1 1 1 1 1 1 1 1 2 0 0 ... Box 10 has the most number of balls with 2 balls.
import math
class Solution:
def countBalls(self, lowLimit: int, highLimit: int) -> int:
max_box_num = int(math.log10(highLimit) + 1) * 9
box_list = [0 for i in range(max_box_num)]
for i in range(lowLimit, highLimit + 1):
i = str(i)
sum_num = 0
for j in i:
sum_num += int(j)
box_list[sum_num - 1] += 1
ball_num_with_max_box = max(box_list)
return ball_num_with_max_box
먼저 highLimit을 이용해 박스의 갯수를 구한다음 box_list에 0을 채워넣어서, 공이 들어갈때마다 +1 을 해주면 된다.
box_list 의 최대 요소 갯수는 highLimit의 자릿수를 구한 뒤 9를 곱해주면 충분한 공간을 확보할 수 있다. 예를들어 82가 highLimit 이면 두자릿 수니까 2에 9를 곱해준다, 왜냐면 십의자리에서 더해서 가장 큰 수는 9 + 9 = 18 이기 때문에 박스의 갯수가 이보다 클 수 없기 때문이다.
이제 int 형을 str 로 만들어서 자릿수마다 iterate 시키고, iterate 할 때마다 sum_num에 값을 더해 최종적으로 나온 값을 box_list의 index로 접근하여 +1 시켜준다.
가장 공이 많이 담긴 박스의 공의 갯수는 파이썬의 max 내장함수로 쉽게 구할 수 있다.