~/problems / Binary search / Binary search on the answer

Split Array Largest Sum

medium ~25 min

Write split_array(nums: list[int], k: int) -> int.

Cut nums into exactly k non-empty contiguous pieces. Each piece has a sum; the cost of a split is the largest of those sums. Return the smallest possible cost.

Example: nums = [5, 1, 1, 6, 2], k = 2 gives 8 ([5, 1, 1] | [6, 2] costs max(7, 8) = 8). With k = 5 every element is its own piece, so the answer is 6.

Constraints: 1 <= k <= len(nums) <= 5 * 10^4, 0 <= nums[i] <= 10^9. Sums can exceed 32 bits, so use 64-bit integers in C++/Java.

Trying split points, or a DP over (prefix, pieces), is far too slow at this size. Aim for O(n log S), where S = sum(nums).

Show hint

instead of choosing cuts, fix a cap c on the piece sums and ask whether k pieces are enough; that question is easy to answer greedily, and its answer only flips once as c grows. (Needing fewer than k pieces is fine: you can always split further, since k <= len(nums).)

Topic: Binary search on the answer. Monotonic feasibility check + search the smallest value that works.

Read the visual guide
0:00
Ctrl ' run · Ctrl ↵ submit
esc