【每日一题Day62】LC1760袋子里最少数目的球 | 二分查找

该博客讨论了一道编程题目,涉及在限制操作次数的情况下如何将含有不同数量球的袋子重新分配,以最小化单个袋子的最大球数。通过二分查找算法,寻找在不超过最大操作次数时能实现的最小最大球数。博客内容涵盖了问题的转化、操作计数方法以及二分查找的实施细节,旨在帮助读者理解并解决此类问题。

袋子里最少数目的球【LC1760】

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.

给你一个整数数组 nums ,其中 nums[i] 表示第 i 个袋子里球的数目。同时给你一个整数 maxOperations

你可以进行如下操作至多 maxOperations 次:

  • 选择任意一个袋子,并将袋子里的球分到 2 个新的袋子中,每个袋子里都有正整数个球。
    • 比方说,一个袋子里有 5 个球,你可以把它们分到两个新袋子里,分别有 1 个和 4 个球,或者分别有 2 个和 3 个球。

你的开销是单个袋子里球数目的 最大值 ,你想要 最小化 开销。

请你返回进行上述操作后的最小开销。

题是永远刷不完的… 尽量把做过的都搞懂吧
2022/12/20

  • 思路:

    • 首先,将题意转化为,当操作次数一定时,求出单个袋子里球的数目的最大值的最小值yyy,那么可以通过二分查找的方法找到最终的yyy,二分查找的下限为1,上限为数组nums中的最大值
    • 当二分查找yyy时,对于第iii个袋子,它装有nums[i]nums[i]nums[i]个球,那么我们需要使其分割的新袋子内球的个数小于等于yyy,所需要的操作数为⌊nums[i]−1y⌋\lfloor \frac{nums[i]-1}{y} \rfloorynums[i]1
      • nums[i]≤ynums[i] \le ynums[i]y时,不需要进行操作
      • y<nums[i]≤yy\lt nums[i] \le yy<nums[i]y时,需要1次操作
      • y<nums[i]≤2yy\lt nums[i] \le 2yy<nums[i]2y时,需要2次操作
    • 那么总操作次数为$ P =\sum_{i=0}^{n-1}\lfloor \frac{nums[i]-1}{y} \rfloor,当,当,当P \le maxOperations$时,调整二分查找的上界,否则调整二分查找的下界
  • 实现

    class Solution {
        public int minimumSize(int[] nums, int maxOperations) {
            int l = 1, r = Arrays.stream(nums).max().getAsInt();
            int res = 0;
            while (l <= r){
                int mid = (r + l) / 2;
                int ops = 0;
                for (int num : nums){
                    ops += (num - 1) / mid;
                }
                if (ops <= maxOperations){
                    res = mid;
                    r = mid - 1;
                }else{
                    l = mid + 1;
                }
            }
            return res;
        }
    }
    
    • 复杂度
      • 时间复杂度:O(nlogC)O(nlogC)O(nlogC)nnn是数组的长度,C是数组中的最大值
      • 空间复杂度:O(1)O(1)O(1)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值