Split array largest sum

November 22, 2022

binary-search

Problem URL: Split array largest sum

We binary search largest sum in range [max(nums), sum(nums)], which is left = max(nums), right = sum(nums).

class Solution:
    def splitArray(self, nums: List[int], k: int) -> int:
        def canPartition(largestSum):
            groups = 1
            curSum = 0
            for num in nums:
                curSum += num
                if curSum > largestSum:
                    groups += 1
                    curSum = num
            return groups <= k

        left, right = max(nums), sum(nums)
        res = right
        while left <= right:
            mid = left+(right-left)//2
            if canPartition(mid):
                res = mid
                right = mid-1
            else:
                left = mid+1
        return res