首页 > 其他分享 >LC1760. Minimum Limit of Balls in a Bag

LC1760. Minimum Limit of Balls in a Bag

时间:2022-12-20 15:45:50浏览次数:61  
标签:Balls nums bag int balls maxOperations two Bag Minimum

利用二分去寻找答案

「二分」的本质是两段性,并非单调性。只要一段满足某个性质,另外一段不满足某个性质,就可以用「二分」。

1760. Minimum Limit of Balls in a Bag

https://leetcode.cn/problems/minimum-limit-of-balls-in-a-bag/

You are given an integer array nums where the i(th) bag contains nums[i] balls. You are also given an integer maxOperations.

You can perform the following operation at most maxOperations times:

  • Take any bag of balls and divide it into two new bags with a positive number of balls.
    • For example, a bag of 5 balls can become two new bags of 1 and 4 balls, or two new bags of 2 and 3 balls.

Your penalty is the maximum number of balls in a bag. You want to minimize your penalty after the operations.

Return the minimum possible penalty after performing the operations.

Example:

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

  • Divide the bag with 8 balls into two bags of sizes 4 and 4. [2,4,8,2] -> [2,4,4,4,2].
  • Divide the bag with 4 balls into two bags of sizes 2 and 2. [2,4,4,4,2] -> [2,2,2,4,4,2].
  • Divide the bag with 4 balls into two bags of sizes 2 and 2. [2,2,2,4,4,2] -> [2,2,2,2,2,4,2].
  • Divide the bag with 4 balls into two bags of sizes 2 and 2. [2,2,2,2,2,4,2] -> [2,2,2,2,2,2,2,2].
    The bag with the most number of balls has 2 balls, so your penalty is 2, and you should return 2.

Constraints:

  • 1 <= nums.length <= 10^5
  • 1 <= maxOperations, nums[i] <= 10^9

Process

将题目要求转换成判定问题,利用二分来解决

Code

class Solution {
private:
    bool check(vector<int>& nums, int &maxOperations,int&k)
    {
        long long ops = 0;
         for (int x: nums) {
                ops += (x - 1) / k;
                if(ops > maxOperations)return false;
            } 
        return true;
    }

public:
    int minimumSize(vector<int>& nums, int maxOperations) {
       //利用二分去找答案
        int l = 1,r = *max_element(nums.begin(), nums.end());
        
        int mid;
        while(l<r){
            mid = (l+r)>>1;
            if(check(nums,maxOperations,mid))r = mid;
            else l = mid+1;
        }
        return l;

    }
};

标签:Balls,nums,bag,int,balls,maxOperations,two,Bag,Minimum
From: https://www.cnblogs.com/hereskiki/p/16994317.html

相关文章