Given an array which consists of non-negative integers and an integer m, you can split the array into m non-empty continuous subarrays. Write an algorithm to minimize the largest sum among these m subarrays.
Note:
If n is the length of array, assume the following constraints are satisfied:
- 1 ≤ n ≤ 1000
- 1 ≤ m ≤ min(50, n)
Examples:
Input:
nums = [7,2,5,10,8]
m = 2
Output:
18
Explanation:
There are four ways to split nums into two subarrays.
The best way is to split it into [7,2,5] and [10,8],
where the largest sum among the two subarrays is only 18.
这道题目诈一看无从下手,因为题目说去拆分数组找最小可能的最大子数组和,有点拗口。翻译过来就是拆成m个子数组,必须连续的,然后这些子数组中最大的和,按照不同的拆法,每次最大的子数组和不同,找到一种算法能够找出最大子数组和的最小值
按照拆分数组的思路就会陷入死胡同,因为太难了,用DFS也找不过来,不过既然这是 一道hard题,想想其他解法
个么直接讲答案,binary search, 怎么个binary search法呢?
First, forget about 分几组的问题,如果单单就是分组,随意分几组,最好是有多少个数字分多少组,那么答案就是这组数字的最大值,最坏呢?最坏就是一组都不分,直接取和就是答案了。好了,在最好和最坏的情况里, 我们先确定一个值,比如就是最好和最坏的平均值,用这个平均值来做sliding window分组,每当你的小组和大于这个平均值了,那么要新开一组了,全部分完之后,看看需要分多少组,如果需要分的组大于规定的组,那么说明这个平均值低了,调高平均值减少组数,如果少于规定可以区分的组,那么就说明平均值高了,我们可以调低平均值增加组合数。来来回回,最终确定这个平均值就行了而不需要知道到底怎么分组。
Code:
class Solution:
def splitArray(self, nums: List[int], m: int) -> int:
left=max(nums)
right=sum(nums)
while left<right:
mid=left+(right-left)//2
count=1
total=0
for num in nums:
total+=num
if total>mid:
total=num
count+=1
if count>m:
left=mid+1
else:
right=mid
return left