Skip to content

Commit 0795585

Browse files
authored
Create split-array-largest-sum.py
1 parent 3ef6be2 commit 0795585

1 file changed

Lines changed: 52 additions & 0 deletions

File tree

Python/split-array-largest-sum.py

Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
# Time: O(nlogs), s is the sum of nums
2+
# Space: O(1)
3+
4+
# Given an array which consists of non-negative integers and an integer m,
5+
# you can split the array into m non-empty continuous subarrays.
6+
# Write an algorithm to minimize the largest sum among these m subarrays.
7+
#
8+
# Note:
9+
# Given m satisfies the following constraint: 1 <= m <= length(nums) <= 14,000.
10+
#
11+
# Examples:
12+
#
13+
# Input:
14+
# nums = [7,2,5,10,8]
15+
# m = 2
16+
#
17+
# Output:
18+
# 18
19+
#
20+
# Explanation:
21+
# There are four ways to split nums into two subarrays.
22+
# The best way is to split it into [7,2,5] and [10,8],
23+
# where the largest sum among the two subarrays is only 18.
24+
25+
class Solution(object):
26+
def splitArray(self, nums, m):
27+
"""
28+
:type nums: List[int]
29+
:type m: int
30+
:rtype: int
31+
"""
32+
def canSplit(nums, m, s):
33+
cnt, curr_sum = 1, 0
34+
for num in nums:
35+
curr_sum += num
36+
if curr_sum > s:
37+
curr_sum = num
38+
cnt += 1
39+
return cnt <= m
40+
41+
left, right = 0, 0
42+
for num in nums:
43+
left = max(left, num)
44+
right += num
45+
46+
while left <= right:
47+
mid = left + (right - left) / 2;
48+
if canSplit(nums, m, mid):
49+
right = mid - 1
50+
else:
51+
left = mid + 1
52+
return left

0 commit comments

Comments
 (0)