[LeetCode] 1742. The maximum number of balls in the box (C++)

1 topic description

You work in a toy factory that produces small balls. There are n balls, numbered from lowLimit to highLimit (including lowLimit and highLimit, ie n == highLimit-lowLimit + 1). There are also an unlimited number of boxes, numbered from 1 to infinity.
Your job is to put each ball into a box, where the box number should be equal to the sum of each number on the ball number. For example, the ball numbered 321 should be placed in the box numbered 3 + 2 + 1 = 6, and the ball numbered 10 should be placed in the box numbered 1 + 0 = 1.
Give you two integers, lowLimit and highLimit, and return the number of balls in the box with the most balls. If there are multiple boxes that satisfy the maximum number of balls, just return the number of balls in any one of the boxes.

2 Example description

2.1 Example 1

Input: lowLimit = 1, highLimit = 10
Output: 2
Explanation:
Box number: 1 2 3 4 5 6 7 8 9 10 11 …the
number of balls: 2 1 1 1 1 1 1 1 1 0 0 …
put the box number 1 There are the most balls, and the number of balls is 2.

2.2 Example 2

Input: lowLimit = 5, highLimit = 15
Output: 2
Explanation:
Box number: 1 2 3 4 5 6 7 8 9 10 11 …
Number of balls: 1 1 1 1 2 2 1 1 1 0 0 …
Numbers 5 and 6 The box contains the most balls, and the number of balls in each box is 2.

2.3 Example 3

Input: lowLimit = 19, highLimit = 28
Output: 2
Explanation:
Box number: 1 2 3 4 5 6 7 8 9 10 11 12 …
Number of balls: 0 1 1 1 1 1 1 1 1 2 0 0 …
Number 10 The box contains the most balls, and the number of balls is 2.

3 Problem solving tips

1 <= lowLimit <= highLimit <= 10^5

4 Problem-solving ideas

Write a function that accumulates the sum of digits, and then substitute it into the calculation.

5 Detailed source code (C++)

class Solution {
    
    
public:
    int arr[101] = {
    
     0 } , index ;
    int funcation( int n )
    {
    
    
        int res = 0 ;
        while( n )
        {
    
    
            res = res + n % 10 ;
            n = n / 10 ;
        }
        return res ;
    }
    int countBalls(int lowLimit, int highLimit) {
    
    
        for ( int i = lowLimit ; i <= highLimit ; i ++ )
        {
    
    
            index = funcation( i ) ;
            arr[index] ++ ;
        }
        int Max = -1 ;
        for ( int i = 0 ; i < 100 ; i ++ )
        {
    
    
            Max = max ( Max , arr[i] ) ;
        }
        return Max ;
    }
};

Guess you like

Origin blog.csdn.net/Gyangxixi/article/details/114132547