"""
https://leetcode.com/problems/split-array-largest-sum/
"""
from typing import List


class Solution:
    def splitArray(self, nums: List[int], m: int) -> int:
        l, r = max(nums), sum(nums)
        while l < r:
            mid = (l + r) // 2
            print(l, r, mid)
            if self.isValid(nums, m, mid):
                r = mid
            else:
                l = mid + 1
        return l

    def isValid(self, nums: List[int], m: int, T: int) -> bool:
        groupSum = 0
        groupCount = 1
        for n in nums:
            if groupSum + n <= T:
                groupSum += n
            else:
                groupCount += 1
                groupSum = n
        return groupCount <= m

"""
https://leetcode.com/problems/split-array-largest-sum/
"""
from typing import List


class Solution:
    def splitArray(self, nums: List[int], m: int) -> int:
        l, r = max(nums), sum(nums)
        while l < r:
            mid = (l + r) // 2
            print(l, r, mid)
            if self.isValid(nums, m, mid):
                r = mid
            else:
                l = mid + 1
        return l

    def isValid(self, nums: List[int], m: int, T: int) -> bool:
        groupSum = 0
        groupCount = 1
        for n in nums:
            if groupSum + n <= T:
                groupSum += n
            else:
                groupCount += 1
                groupSum = n
        return groupCount <= m

https://leetcode.com/problems/split-array-largest-sum/