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.
----------------------------------------------------------------------------------------
这好像是一道很著名的问题,明显的解法就是DP,但是刚开始脑子进水,用f(x,y,p)表示从下标x到下标y分p份时候最大字段和的最小结果,然后生生搞成了5维DP。降维也很简单,利用f(x,p)表示从下标0到下标x分成p份时候最大字段和的最小结果。那么
f(x,p) = min{max[f(x0,p-1), sum(nums[x0+1...x])]},其中0<=x0<x,所以有三个变量:x0依赖于x,x依赖于p,所以三重循环,就先p,再x,最内层x0,最好f(x,p)写成f(p,x),最终codes偷懒没有改:
class Solution:
def splitArray(self, nums, m: int) -> int:
l = len(nums)
f = [[0 for j in range(m+1)] for i in range(l+1)]
accu = [nums[0] for i in range(l)]
for i in range(1,l):
accu[i] = accu[i-1]+nums[i]
for i in range(l):
f[i][1] = accu[i]
for p in range(2,m+1):
for x in range(p-1,l):
f[x][p] = accu[l-1]
for x0 in range(x):
f[x][p] = min(f[x][p], max(f[x0][p-1],accu[x]-accu[x0]))
return f[l-1][m]
s = Solution()
print(s.splitArray(nums = [7,2,5,10,8], m = 2))
DP的问题也很明显,并没有利用单调性的特点,既然单调性,那就二分走起啊:
class Solution:
def get_partion_cnt(self, nums, threshold):
res, cur = 0, 0
for num in nums:
if (cur + num <= threshold):
cur += num
else:
res += 1
cur = num
if (cur > 0):
res += 1
return res
def splitArray(self, nums, m: int) -> int:
total, ma = sum(nums), max(nums)
# ma<=res<=total
l, r = ma, total
while (l <= r):
mid = l + ((r - l) >> 1)
pa = self.get_partion_cnt(nums, mid)
if (pa <= m):
r = mid - 1
else:
l = mid + 1
return l