-
Notifications
You must be signed in to change notification settings - Fork 17
Expand file tree
/
Copy pathsplit-array-largest-sum.py
More file actions
41 lines (29 loc) · 974 Bytes
/
split-array-largest-sum.py
File metadata and controls
41 lines (29 loc) · 974 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
from typing import List
class Solution:
def splitArray(self, nums: List[int], m: int) -> int:
def condition(subarray_sum: int) -> bool:
# we canot construct m subarrays -> False
# else -> True
cur_sum = 0
pos = 0
count = 1
while pos < len(nums):
if cur_sum > subarray_sum:
return True
if cur_sum + nums[pos] > subarray_sum:
cur_sum = nums[pos]
count += 1
else:
cur_sum += nums[pos]
if count > m:
return True
pos += 1
return False
left, right = max(nums), sum(nums)
while left < right:
middle = left + (right - left) // 2
if condition(middle):
left = middle + 1
else:
right = middle
return left