能用贪心算法!!! left是数组中的最大值,right是数组和。通过canSplit来改变left和right(此时的他们的桥梁是平均值),最终他们会收敛到一个值。
class Solution:
def splitArray(self, nums, m):
"""
:type nums: List[int]
:type m: int
:rtype: int
"""
left=max(nums)
right=sum(nums)
while left < right:
mid=left+(right-left)//2
if self.canSplit(nums,m,mid):
right = mid
else:
left=mid+1
return left
def canSplit(self,nums,m,sum1):
cnt=1
curSum=0
for i in range(len(nums)):
curSum+=nums[i]
if curSum>sum1:
curSum=nums[i]
cnt+=1
if cnt>m: return False
return True