You are given an integer n.
Each number from 1 to n is grouped according to the sum of its digits.
Return the number of groups that have the largest size.
정수 n 이 주어집니다.
1부터 n까지의 각 숫자는 그 숫자의 자릿수 합(각 자리 숫자의 합) 에 따라 그룹으로 묶입니다.
가장 크기가 큰(가장 많은 숫자를 포함한) 그룹이 몇 개 인지 반환하세요.
[1,10], [2,11], [3,12], [4,13], [5], [6], [7], [8], [9]
이 중에서 크기가 2인 그룹이 4개 이므로 답은 4.
class Solution:
def countLargestGroup(self, n: int) -> int:
cnt = [0] * 37 # 해당 자리수 합을 가진 숫자 갯수
ans = 0 # 가장 큰 크기 그룹의 개수
for i in range(1 , n + 1):
ans = 0 # 가장 긴 완전 부분 집합의 개수를 기록
x = i
while x:
ans += x % 10
x //= 10
cnt[ans] += 1
largest_group = max(cnt)
return cnt.count(largest_group)
| i (현재 숫자) | ans 초기값 | x 초기값 | while 1회 (ans += x % 10, x //= 10) | while 2회 | while 3회 | 최종 ans (자릿수 합) | cnt[ans] 증가 후 |
|---|---|---|---|---|---|---|---|
| 1 | 0 | 1 | ans = 1, x = 0 | — | — | 1 | cnt[1] = 1 |
| 2 | 0 | 2 | ans = 2, x = 0 | — | — | 2 | cnt[2] = 1 |
| 3 | 0 | 3 | ans = 3, x = 0 | — | — | 3 | cnt[3] = 1 |
| 4 | 0 | 4 | ans = 4, x = 0 | — | — | 4 | cnt[4] = 1 |
| 5 | 0 | 5 | ans = 5, x = 0 | — | — | 5 | cnt[5] = 1 |
| 6 | 0 | 6 | ans = 6, x = 0 | — | — | 6 | cnt[6] = 1 |
| 7 | 0 | 7 | ans = 7, x = 0 | — | — | 7 | cnt[7] = 1 |
| 8 | 0 | 8 | ans = 8, x = 0 | — | — | 8 | cnt[8] = 1 |
| 9 | 0 | 9 | ans = 9, x = 0 | — | — | 9 | cnt[9] = 1 |
| 10 | 0 | 10 | ans = 0, x = 1 | ans = 1, x = 0 | — | 1 | cnt[1] = 2 |
| 11 | 0 | 11 | ans = 1, x = 1 | ans = 2, x = 0 | — | 2 | cnt[2] = 2 |
| 12 | 0 | 12 | ans = 2, x = 1 | ans = 3, x = 0 | — | 3 | cnt[3] = 2 |
| 13 | 0 | 13 | ans = 3, x = 1 | ans = 4, x = 0 | — | 4 | cnt[4] = 2 |
최종
cnt요약: 인덱스 1~4 는 2, 5~9 는 1 →largest_group = 2,cnt.count(2) = 4