Leetcode: 410. Split Array Largest Sum
Problem Statement
- Is there an alternative problem easier to solve? Given a candidate answer, check if it is possible to partition the array in at most \(m\) parts. If so, the candidate is valid, otherwise you have to increase it. The optimal answer can be found using a Binary Search. Time complexity is \(O(n \log \sum a[i])\) and space is \(O(1)\).
class Solution:
def splitArray(self, nums: List[int], M: int) -> int:
N = len(nums)
s = max(nums)
e = sum(nums)
def valid(m):
cnt = i = cur = 0
while i < N:
if cur + nums[i] <= m:
cur += nums[i]
else:
cur = nums[i]
cnt += 1
i += 1
return cnt < M
while s < e:
m = s + (e - s) // 2
if valid(m):
e = m
else:
s = m + 1
return s