【LeetCode】1760. Minimum number of balls in the bag

topic

You are given an integer array nums, where nums[i] represents the number of balls in the i-th bag. Also gives you an integer maxOperations.

You can perform the following operations up to maxOperations times:
select any bag and divide the balls in the bag into 2 new bags, each bag containing a positive integer number of balls.
For example, if there are 5 balls in a bag, you can divide them into two new bags with 1 and 4 balls respectively, or 2 and 3 balls respectively.
Your overhead is the maximum number of balls in a single bag, and you want to minimize the overhead.

Please return the minimum cost after performing the above operations.

Example 1:

Input: nums = [9], maxOperations = 2
Output: 3
Explanation:

  • Divide the bag of 9 balls into bags of 6 and 3 balls. [9] -> [6,3] .
  • Divide the bag of 6 balls into bags of 3 and 3 balls. [6,3] -> [3,3,3] .
    The bag with the most balls contains 3 balls, so the cost is 3 and 3 is returned.

Example 2:

Input: nums = [2,4,8,2], maxOperations = 4
Output: 2
Explanation:

  • Divide the bag of 8 balls into bags of 4 and 4 balls. [2,4,8,2] -> [2,4,4,4,2] .
  • Divide the bag of 4 balls into bags of 2 and 2 balls. [2,4,4,4,2] -> [2,2,2,4,4,2] .
  • Divide the bag of 4 balls into bags of 2 and 2 balls. [2,2,2,4,4,2] -> [2,2,2,2,2,4,2] .
  • Divide the bag of 4 balls into bags of 2 and 2 balls. [2,2,2,2,2,4,2] -> [2,2,2,2,2,2,2,2] .
    The bag with the most balls contains 2 balls, so the cost is 2 and 2 is returned.

Example 3:

Input: nums = [7,17], maxOperations = 2
Output: 7

hint:

1 <= nums.length <= 105
1 <= maxOperations, nums[i] <= 109

answer

Use binary search to
divide the balls by maxOperations times to ensure that the maximum number of balls in the bag is the smallest.

That is to say, the balls in each bag are divided into y bags. If there are not enough y balls, no operation will be performed.
So the goal is to find a suitable y value that can satisfy the requirement that the number of ball distributions does not exceed maxOperations and the cost of each portion is minimal.

class Solution {
    
    
public:
    int minimumSize(vector<int>& nums, int maxOperations) {
    
    
        int left = 0;
        int right = *max_element(nums.begin(),nums.end())+1;
        int res = 0;
        while(left+1 != right)
        {
    
    
            int mid = left+((right-left)>>1);
            //cout<<left<<"=="<<mid<<"=="<<right<<"==>";
            int opr = 0;
            for(int it:nums)
            {
    
    
                opr += it/mid + (it%mid!=0) -1;
            }
            if(opr <= maxOperations)
            {
    
    
                right = mid;
                res = mid;
            }
            else
                left = mid;
            //cout<<left<<" "<<right<<endl;
        }
        return res;
    }
};

Guess you like

Origin blog.csdn.net/qq_45972928/article/details/126203095