LeetCode-1742. Maximum Number of Balls in a Box (Maximum Number of Balls in a Box)-Analysis and Code (Java)

LeetCode-1742. Maximum Number of Balls in a Box [Maximum Number of Balls in a Box]-Analysis and Code [Java]

1. Topic

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.

Example 1:

输入:lowLimit = 1, highLimit = 10
输出:2
解释:
盒子编号:1 2 3 4 5 6 7 8 9 10 11 ...
小球数量:2 1 1 1 1 1 1 1 1 0  0  ...
编号 1 的盒子放有最多小球,小球数量为 2 。

Example 2:

输入:lowLimit = 5, highLimit = 15
输出:2
解释:
盒子编号:1 2 3 4 5 6 7 8 9 10 11 ...
小球数量:1 1 1 1 2 2 1 1 1 0  0  ...
编号 5 和 6 的盒子放有最多小球,每个盒子中的小球数量都是 2 。

Example 3:

输入:lowLimit = 19, highLimit = 28
输出:2
解释:
盒子编号:1 2 3 4 5 6 7 8 9 10 11 12 ...
小球数量:0 1 1 1 1 1 1 1 1 2  0  0  ...
编号 10 的盒子放有最多小球,小球数量为 2 。

prompt:

  • 1 <= lowLimit <= highLimit <= 105

Source: LeetCode (LeetCode)
Link: https://leetcode-cn.com/problems/maximum-number-of-balls-in-a-box The
copyright is owned by LeetCode . For commercial reprints, please contact the official authorization. For non-commercial reprints, please indicate the source.

Two, analysis and code

1. Add one by one

(1) Thinking

Put the balls into the box one by one and judge.

(2) Code

class Solution {
    
    
    public int countBalls(int lowLimit, int highLimit) {
    
    
        int lenMax = 46;
        int [] box = new int[lenMax];
        Arrays.fill(box, 0);
        for (int i = lowLimit; i <= highLimit; i++) {
    
    
            int s = 0;
            for (int num = i; num > 0; num /= 10)
                s += num % 10;
            box[s]++;
        }
        int ans = 0;
        for (int i = 0; i < lenMax; i++)
            ans = Math.max(ans, box[i]);
        return ans; 
    }
}

(3) Results

Execution time: 24 ms, beating 93.49% of users
in all Java submissions ; memory consumption: 35.4 MB, beating 72.49% of users in all Java submissions.

Three, other

Nothing.

Guess you like

Origin blog.csdn.net/zml66666/article/details/113804577