LeetCode 1760. Minimum Limit of Balls in a Bag - 二分查找(Binary Search)系列题19
Posted CP Coding
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetCode 1760. Minimum Limit of Balls in a Bag - 二分查找(Binary Search)系列题19相关的知识,希望对你有一定的参考价值。
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 of1
and4
balls, or two new bags of2
and3
balls.
- For example, a bag of
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
题目大意:给定一个数组nums, 数组的长度n表示有n个袋子,第i个元素表示第i个袋子里装有nums[i]个球。现在允许你对袋子的球动手脚,动手脚的次数不能超过给定的上限maxOperations。所谓动手脚就是说每次你可以任意挑一个袋子,然后把袋子的球分装到两个袋子里(可以任意分装但要求每个袋子必须都有至少一个球)。到最后剩球最多的那个袋子的球的个数是对你的惩罚数,现在你的任务是尽可能地使惩罚数最小,返回这个最小惩罚数。
搞懂题目就会发现其实这题跟LeetCode 1011. Capacity To Ship Packages Within D Days很像。最理想的状态就是最后每个袋子里都只有一个球即惩罚数就为1,最不理想的状态就是没动任何手脚那惩罚数就原数组里的最大值,因此我们要做的就是从1到数组最大值maxNum的区间范围内找到一个最小的且满足条件的值,这很自然地想到了二分查找法。
取[1, maxNum]的中间值mid=(1 + maxNum) // 2,计算当惩罚数为mid时要动几次手脚才能使所有袋子的球个数都小于等于mid,要是动手脚次数小于等于maxOperations说明可以使惩罚数小于等于mid,则继续在左半区间查找更小的可能的惩罚数;要是动手脚次数大于maxOperations说明无法使惩罚数小于等于mid,则继续在右半区间查找更大的可能的惩罚数。
如何判断惩罚数为mid 时需要几次操作才能使所有袋子球的个数小于等于mid?遍历整个数组nums,如果球个数num小于等于mid则为0次,如果球个数num大于mid,则需要的次数为(num - 1) // mid。
class Solution:
def minimumSize(self, nums: List[int], maxOperations: int) -> int:
l, r = 1, max(nums)
while l <= r:
mid = (l + r) // 2
total = 0
for num in nums:
if num > mid:
total += (num - 1) // mid
if total > maxOperations:
l = mid + 1
else:
r = mid - 1
return l
以上是关于LeetCode 1760. Minimum Limit of Balls in a Bag - 二分查找(Binary Search)系列题19的主要内容,如果未能解决你的问题,请参考以下文章