LeetCode 1760: Minimum Limit of Balls in a Bag (二分法经典题)

  1. Minimum Limit of Balls in a Bag
    Medium
    You are given an integer array nums where the ith 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 1:

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

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

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 an you should return 2.
    Example 3:

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

Constraints:

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

解法1:
二分法。
首先我们从0到1e9+7用二分法,来看其中某个数是方案中的某袋子中的最大数目的话(maximum number of balls in a bag),是否满足要求(即划分数<=maxOperations)。可以看出,如果某数x<=maxOperations的话,那么x+1, x+2, …肯定也满足,但x-1及以下就未必满足。所以可以用二分法。
注意:
(nums[i] - 1) / mid 为该bag里的数目(nums[i])要细分到每堆为mid的数目。

class Solution {
public:
    int minimumSize(vector<int>& nums, int maxOperations) {
        int start = 0, end = 1e9 + 7;
        while (start + 1 < end) {
            int mid = start + (end - start) / 2;
            long long cnt = 0;
            for (int i = 0; i < nums.size(); ++i) {
                cnt += (nums[i] - 1) / mid;
            }
            if (cnt <= maxOperations) {
                end = mid;
            } else {
                start = mid;
            }
        }
        
        return end;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值