โจทย์
มีลูกบอลหมายเลข l ถึง r ใส่ในกล่องที่หมายเลข = ผลรวมหลักของหมายเลขลูกบอล (เช่น 123 → กล่อง 6) หากมี l และ r ให้หาจำนวนลูกบอลมากที่สุดในกล่องใดกล่องหนึ่ง
ตัวอย่าง: l=15, r=25 → กล่อง 6 และ 7 มีลูกบอลมากที่สุด = 2 ลูก
อัลกอริธึม
- ใช้ Dictionary นับจำนวนลูกบอลต่อกล่อง
- วน
iจากlถึงrคำนวณ Digit Sum - เพิ่ม Count ใน Dictionary
- คืนค่า Max ของ Values
โค้ด Python
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.values())
l, r = 15, 25
print(solve(l, r)) # Output: 2
Input / Output
Input: 15, 25
Output: 2