Split Array Largest Sum
Picture
Split [3, 2, 4] into two consecutive groups. A maximum sum of 4 requires three groups. A maximum of 5 allows [3, 2] and [4]. Any larger cap also works: the yes/no answers have a boundary.
Predict
Why is “can we fit into at most k groups under cap C?” easier than directly choosing the best split?
Walk through the small example
For a fixed cap, greedily extend a group until the next value would overflow it. This minimizes how many groups are needed. Then binary search locates the smallest cap passing the test.
Mental model and complete Python solution
With nonnegative values, starting a new group earlier cannot let the first group cover more items. Inductively, greedy reaches at least as far after each group as any feasible partition. Search between max(nums) and sum(nums). If a cap works with fewer than k groups, split some groups further: nonnegative sums cannot grow, and k ≤ n ensures enough items. Thus at-most-k feasibility also serves the exactly-k contract.
What the function promises: nums is nonempty and nonnegative; 1 ≤ k ≤ len(nums). Return the smallest possible largest sum across exactly k nonempty consecutive groups.
def split_largest_sum(nums, k):
if not nums or not 1 <= k <= len(nums) or any(x < 0 for x in nums):
raise ValueError("Need nonnegative values and 1 <= k <= n")
def fits(cap):
groups, subtotal = 1, 0
for value in nums:
if subtotal + value > cap:
groups += 1
subtotal = 0
subtotal += value
return groups <= k
low, high = max(nums), sum(nums)
while low < high:
middle = (low + high) // 2
if fits(middle):
high = middle
else:
low = middle + 1
return low
assert split_largest_sum([3, 2, 4], 2) == 5
assert split_largest_sum([7, 2, 5, 10, 8], 2) == 18
assert split_largest_sum([0, 0], 2) == 0
Work and storage: O(n log(S − M + 2)) time and O(1) auxiliary space, where S is the sum and M the maximum. Feasibility itself is one linear scan.
When to recognize it: If a cap works, every larger cap works. Search the first working cap, not an array position.
Check before applying it: Nonnegative values make the greedy packing test safe. With negative values, a later item could rescue an overflowing group.
Change one rule
Could the same style solve a minimum eating-speed problem?
See what changes
Yes, if you prove that increasing speed can only improve feasibility. Define a separate hours-needed test, then search the first speed passing it. The reusable idea is a monotone decision boundary, not the particular grouping code.
Connect
invariants: The first working answer stays inside the remaining search range.
Swim in Rising Water: A water level also turns reachability from impossible to possible.
Problem reference: Split Array Largest Sum (Hard). The walkthrough and Python solution above are original course material.