LeetCode 1760. [Python] Minimum Limit of Balls in a Bag
原题链接
中等
作者:
徐辰潇
,
2021-02-15 00:26:12
,
所有人可见
,
阅读 703
class Solution:
def minimumSize(self, nums: List[int], maxOperations: int) -> int:
#TC: O(log (M*n)) M=max(nums) n=len(nums)
#SC: O(1)
#binary search to find a M
#bags which contains balls more than M will be cut by certain operations
#Note it must be evenly cut. Number of cut required is (math.ceil(nums[i] / M) - 1) for i-th
left = 1
right = max(nums)
def countCut(Max):
cut = 0
for ele in nums:
if ele > Max:
cut = cut + math.ceil(ele / Max) - 1
return cut
while (left + 1 < right):
mid = left + (right - left) // 2
cut = countCut(mid)
#Here note that mid and cut is not 1-1 mapping!!
#Even with the same cut, there may be different values for mid
#Thus if cut == maxOperations, the mid still can be smaller.
#WE CANNOT WRITE
# if cut == maxOperatios:
# return mid
if cut <= maxOperations:
right = mid
else:
left = mid
cut_left = countCut(left)
cut_right = countCut(right)
if cut_right <= maxOperations:
return right
else:
return left