classSolution: defsplitArray(self, nums: List[int], m: int) -> int: defgroup(mid): sums, cnt = 0, 1 for i in nums: if sums + i > mid: cnt += 1 sums = i else: sums += i return cnt
left, right = max(nums),sum(nums) while left < right: mid = (left + right) // 2 sums, cnt = 0, 1 for i in nums: if sums + i > mid: cnt += 1 sums = i else: sums += i if group(mid) <= m: right = mid else: left = mid + 1 return left
完整代码
如果不想再分函数,可以这么写
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
classSolution: defsplitArray(self, nums: List[int], m: int) -> int: left, right = max(nums),sum(nums) while left < right: mid = (left + right) // 2 sums, cnt = 0, 1 for i in nums: if sums + i > mid: cnt += 1 sums = i else: sums += i if cnt <= m: right = mid else: left = mid + 1 return left