Skip to content
mlmentorship

Split Array Largest Sum

Split an array into `k` nonempty continuous parts. Make the largest part sum as small as possible.

Published · 10 min read ·Specialist ·Advanced

ML breadth · active recall

Practice before you read

8 minutes. Explain the mechanism, why it works, when it fails, and one alternative.

ML breadth · closed-book attempt

Split Array Largest Sum

Explain the mechanism, why it works, when it fails, and one alternative.

Problem

Input. A nonempty list nums of nonnegative integers and an integer parts with 1 <= parts <= len(nums). Output. Return the smallest achievable value of the largest group sum across all valid partitions. Rules. Use exactly parts groups, each nonempty and contiguous, preserving the original order. Every input occurrence belongs to exactly one group. Zeros and duplicate values are allowed. Do not modify the list. Return only the optimal largest sum, not the split positions. Example. [7, 2, 5, 10, 8] with parts = 2 returns 18. The split [7, 2, 5] and [10, 8] has sums 14 and 18; no split lowers the largest sum further.

08:00recommended time

Closing or reloading clears the scratchpad. Only score, weak rubric dimensions, attempt count, and retry date can be stored locally.

30-second answer map

Binary-search the first feasible capacity because the greedy number of contiguous parts never increases when capacity grows.

Problem trace

A failed capacity rules out every smaller capacity for these nonnegative values

Worked example: the capacity predicate becomes feasible at the correct boundaryFill each group until the next item would exceed the capacity. At seventeen, the final two items need separate groups. At eighteen, they fit together and only two groups are needed. Search for the first capacity whose group count meets the limit.Keep input order; open a row onlywhen its capacity would overflowCapacity 17725Sum 1410Sum 108Sum 83 groups; at most 2 allowedCapacity 18725Sum 14108Sum 182 groups; at most 2 allowed
Read it this way: Fill each group until the next item would exceed the capacity. At seventeen, the final two items need separate groups. At eighteen, they fit together and only two groups are needed. Search for the first capacity whose group count meets the limit. Which cut disappears when capacity rises from seventeen to eighteen?
Full interview answer 10 min read
Reading depth

Split an array into a fixed number of contiguous groups while making the largest group sum as small as possible.

Problem

Input. A nonempty list nums of nonnegative integers and an integer parts with 1 <= parts <= len(nums).

Output. Return the smallest achievable value of the largest group sum across all valid partitions.

Rules. Use exactly parts groups, each nonempty and contiguous, preserving the original order. Every input occurrence belongs to exactly one group. Zeros and duplicate values are allowed. Do not modify the list. Return only the optimal largest sum, not the split positions.

Example. [7, 2, 5, 10, 8] with parts = 2 returns 18. The split [7, 2, 5] and [10, 8] has sums 14 and 18; no split lowers the largest sum further.

Picture

For [7,2,5,10,8] and two groups, capacity 17 needs three groups: [7,2,5], [10], [8]. Capacity 18 allows [7,2,5], [10,8].

Problem trace

A failed capacity rules out every smaller capacity for these nonnegative values

Input and goalSplit an array into `k` nonempty continuous parts. Make the largest part sum as small as possible.
Initialize answer boundsCapacity must cover the largest value, 10. Capacity 32 fits the whole array.
70215210384
boundslo = 10, hi = 32midpoint(10 + 32) // 2 = 21partitionnot tested yet
bounds
lo = 10, hi = 32
midpoint
(10 + 32) // 2 = 21
partition
not tested yet

Recognize it
Use it when asked to minimize a numeric capacity or maximum load, and a candidate limit can be checked greedily with feasibility changing only once as the limit increases.
Keep true
Every limit below lo is infeasible, at least one feasible answer lies at or below hi, and parts_needed(limit) is nonincreasing; each midpoint decision preserves the smallest feasible limit inside [lo, hi].
Reuse it
For minimize-the-maximum problems, search the answer when a greedy capacity check is monotone: feasible moves the upper bound down, infeasible moves the lower bound above the candidate.
Capacity must cover the largest value, 10. Capacity 32 fits the whole array. Step through the frames to watch the state change. The last frame shows the answer or the stopping condition.
Check: Why does needing three parts at capacity seventeen rule out every smaller capacity under the stated assumptions?
Reference drawing

Problem trace

A failed capacity rules out every smaller capacity for these nonnegative values

Worked example: the capacity predicate becomes feasible at the correct boundaryFill each group until the next item would exceed the capacity. At seventeen, the final two items need separate groups. At eighteen, they fit together and only two groups are needed. Search for the first capacity whose group count meets the limit.Keep input order; open a row onlywhen its capacity would overflowCapacity 17725Sum 1410Sum 108Sum 83 groups; at most 2 allowedCapacity 18725Sum 14108Sum 182 groups; at most 2 allowed
Execution trace
Input and goalSplit an array into `k` nonempty continuous parts. Make the largest part sum as small as possible.
Initialize answer boundsCapacity must cover the largest value, 10. Capacity 32 fits the whole array.
70215210384
boundslo = 10, hi = 32midpoint(10 + 32) // 2 = 21partitionnot tested yet
bounds
lo = 10, hi = 32
midpoint
(10 + 32) // 2 = 21
partition
not tested yet

Recognize it
Use it when asked to minimize a numeric capacity or maximum load, and a candidate limit can be checked greedily with feasibility changing only once as the limit increases.
Keep true
Every limit below lo is infeasible, at least one feasible answer lies at or below hi, and parts_needed(limit) is nonincreasing; each midpoint decision preserves the smallest feasible limit inside [lo, hi].
Reuse it
For minimize-the-maximum problems, search the answer when a greedy capacity check is monotone: feasible moves the upper bound down, infeasible moves the lower bound above the candidate.
Capacity must cover the largest value, 10. Capacity 32 fits the whole array. Step through the frames to watch the state change. The last frame shows the answer or the stopping condition.
Check: Why does needing three parts at capacity seventeen rule out every smaller capacity under the stated assumptions?
Read it this way: Fill each group until the next item would exceed the capacity. At seventeen, the final two items need separate groups. At eighteen, they fit together and only two groups are needed. Search for the first capacity whose group count meets the limit. Which cut disappears when capacity rises from seventeen to eighteen?

With nonnegative entries, extending each group as far as capacity permits minimizes the required group count. Increasing capacity cannot increase that count. Any valid grouping with fewer groups can be split further without increasing its largest sum. Therefore, testing “at most” groups also solves the exact-count task.

Code

def split_array_largest_sum(nums: list[int], parts: int) -> int:
   def parts_needed(limit: int) -> int:
      used = 1
      total = 0
      for num in nums:
         if total + num > limit:
            used += 1
            total = 0
         total += num
      return used

   left, right = max(nums), sum(nums)
   while left < right:
      middle = (left + right) // 2
      if parts_needed(middle) <= parts:
         right = middle
      else:
         left = middle + 1
   return left

Cost: scalar operations and constant workspace, where and . Integer bit costs are excluded.

Change the Requirement

Return the Exact Groups

New task: Return a witness with exactly parts groups.

Picture and change: Find capacity, form maximal groups, then split groups until the required count is reached.

Code: Retain the original nonnegative-input contract.

def split_with_groups(nums: list[int], parts: int):
   limit = split_array_largest_sum(nums, parts)
   groups, current, total = [], [], 0
   for value in nums:
      if current and total + value > limit:
         groups.append(current)
         current, total = [], 0
      current.append(value)
      total += value
   groups.append(current)
   extra = parts - len(groups)
   result = []
   for group in groups:
      take = min(extra, len(group) - 1)
      result.extend([[value] for value in group[:take]])
      result.append(group[take:])
      extra -= take
   return limit, result

Check: split_with_groups([0,0,0], 3) returns (0, [[0], [0], [0]]).

Use when: Boundaries are required; witness storage adds .

Permit Negative Entries

New task: Minimize the same maximum with signed integers.

Picture and change: Replace greedy capacity tests with exact prefix-partition dynamic programming.

Code: Compare every possible last-group boundary.

def split_signed(nums: list[int], parts: int) -> int:
   if not 1 <= parts <= len(nums):
      raise ValueError("parts must be between one and the input length")
   prefix = [0]
   for value in nums:
      prefix.append(prefix[-1] + value)
   previous = [float("inf")] * (len(nums) + 1)
   previous[0] = -float("inf")
   for count in range(1, parts + 1):
      current = [float("inf")] * (len(nums) + 1)
      for end in range(count, len(nums) + 1):
         current[end] = min(
            max(previous[cut], prefix[end] - prefix[cut])
            for cut in range(count - 1, end)
         )
      previous = current
   return previous[-1]

Check: split_signed([5,-4], 1) returns 1; the original lower bound max(nums)=5 is invalid.

Use when: Negative entries invalidate greedy reasoning. Costs become time and workspace.

Reconstruct

Why initialize the empty-prefix maximum to negative infinity in the signed version?

Reasoned answer

Before any group exists, its maximum must not constrain a real negative group sum. Starting at zero would incorrectly change split_signed([-5,-4], 1) from -9 to 0. Positive infinity marks unreachable states; finite reachable results remain integers.