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