0410. Split Array Largest Sum
Hard | Binary Search | 32 ms (92.40%), 14.3 MB (65.39%)
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.
Input: nums = [1,2,3,4,5], m = 2
Output: 9
Input: nums = [1,4,4], m = 3
Output: 4class Solution:
def splitArray(self, nums: List[int], m: int) -> int:
# ==================================================
# Binary Search =
# ==================================================
# time : O(nlog(m)), m is the search space
# space : O(1)
l, r = max(nums), sum(nums)
while l < r:
mid = (l + r) // 2
count, groups = 0, 1
for num in nums:
count += num
if count > mid:
count = num
groups += 1
if groups > m: break
if groups <= m: r = mid
else: l = mid + 1
return lLast updated