0410. Split Array Largest Sum
Hard | Binary Search | 32 ms (92.40%), 14.3 MB (65.39%)
Source: LeetCode - Aplit Array Largest Sum GitHub: Solution / Performance
Given an array nums
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.
Same as LeetCode 1011
Boundary / Search Space
Left (Minimum) = MAX number (cannot seperate a single number) Right (Maximum) = TOTAL amount
Condition
While Loop = Left < Right
Return Value
Left
class 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 l
Last updated
Was this helpful?