Split Array Largest Sum solution explained
Split Array Largest Sum asks you to cut an array of non-negative integers into k non-empty contiguous pieces so that the largest piece sum is as small as possible. The quick solution binary searches that largest sum between max(nums) and sum(nums): for a candidate limit, a greedy left-to-right pass counts the fewest pieces that keep every piece within the limit, and the smallest limit needing at most k pieces is the answer. That runs in O(n log S) time and O(1) extra space, where S is the total; a partition DP in O(k · n²) is the slower but more general alternative.
By Evin JohnPublished 8 min read
The problem in our words
Given an array of n non-negative integers and a number k between 1 and n, place k - 1 cuts between elements so the array becomes k non-empty runs of consecutive elements. Each run has a sum; the cost of the split is the biggest of those sums. Return the smallest cost any split can achieve.
| Array | k | Answer | A best split |
|---|---|---|---|
| [6, 2, 7, 1, 3, 5] | 3 | 8 | [6, 2] [7, 1] [3, 5] |
| [3, 1, 4, 1, 5] | 2 | 8 | [3, 1, 4] [1, 5] |
| [3, 1, 4, 1, 5] | 3 | 5 | [3, 1] [4, 1] [5] |
| [0, 0, 6] | 3 | 6 | [0] [0] [6] |
What the question is really testing
Two things. First, whether you can set up a partition DP cleanly, because that is the natural first answer and shows you understand the structure. Second, whether you know the "binary search on the answer" pattern, which turns an optimization problem into a yes-or-no check. Strong candidates explain why the check is monotonic and why the greedy check is optimal, rather than only reciting the code. The same pattern appears under other names (splitting work among workers, painting boards, shipping parcels), so interviewers like it as a transferable idea.
First answer: partition DP
Let best[j][i] be the smallest possible cost when the first i elements are cut into j pieces. The last piece is some run nums[p:i]; everything before it is a j - 1 piece split of the first p elements. So best[j][i] is the minimum over p of max(best[j - 1][p], sum of nums[p:i]). Prefix sums make each range sum O(1). There are k · n states and each tries up to n cut points.
def split_array_dp(nums, k):
n = len(nums)
prefix = [0]
for x in nums:
prefix.append(prefix[-1] + x)
INF = float('inf')
# best[j][i]: smallest possible largest part when nums[:i] is cut into j parts
best = [[INF] * (n + 1) for _ in range(k + 1)]
best[0][0] = 0
for j in range(1, k + 1):
for i in range(j, n + 1):
for p in range(j - 1, i): # the last part is nums[p:i]
cand = max(best[j - 1][p], prefix[i] - prefix[p])
if cand < best[j][i]:
best[j][i] = cand
return best[k][n]This is correct for any numbers, including negatives, and it is a solid answer when n is a few hundred. The space can be cut to two rows, since row j only reads row j - 1. For larger inputs the interviewer will usually ask for something faster, and that is where the search comes in.
Turning it into a yes-or-no question
Instead of asking for the best cost, ask: can the array be split into at most k pieces with no piece above L? Three facts make this useful.
- The answer is bracketedNo split can beat max(nums), since the biggest element sits in some piece, and one piece holding everything costs sum(nums).
- The check is monotonicIf limit L works, any larger limit works with the same cuts. So the limits that work form a range [answer, sum], and binary search finds its left end.
- Greedy answers the checkScan left to right and keep adding numbers to the current piece until the next one would push it past L; then start a new piece. This uses the fewest pieces possible for that limit.
Why is the greedy pass optimal? Compare it with any valid split under the same limit. The greedy first piece ends at or after the other split's first piece, because greedy stops only when it must. By the same argument, after each piece greedy is never behind, so it cannot use more pieces. And "at most k" is enough: if greedy uses fewer than k pieces, some piece has two or more elements (because k is at most n), and splitting it cannot raise any sum when the numbers are non-negative. Repeat until there are exactly k.
def split_array(nums, k):
def parts_needed(limit): # fewest parts if no part may exceed limit
parts, running = 1, 0
for x in nums:
if running + x > limit: # x cannot join the current part
parts += 1
running = 0
running += x
return parts
lo, hi = max(nums), sum(nums)
while lo < hi:
mid = (lo + hi) // 2
if parts_needed(mid) <= k:
hi = mid # mid works, so the answer is mid or lower
else:
lo = mid + 1
return loFor [6, 2, 7, 1, 3, 5] with k = 3 the range starts as 7 to 24. Limit 15 needs 2 pieces, so the answer is at most 15. Limit 11 needs 3, limit 9 needs 3 and limit 8 needs 3, so the top keeps coming down. Limit 7 needs 5 pieces, which is too many, so the bottom moves up to 8 and the search stops at 8.
#include <algorithm>
#include <vector>
using namespace std;
int splitArray(const vector<int>& nums, int k) {
long long lo = 0, hi = 0;
for (int x : nums) {
lo = max(lo, static_cast<long long>(x));
hi += x;
}
auto fits = [&](long long limit) {
int parts = 1;
long long running = 0;
for (int x : nums) {
if (running + x > limit) {
++parts;
running = 0;
}
running += x;
}
return parts <= k;
};
while (lo < hi) {
long long mid = lo + (hi - lo) / 2;
if (fits(mid)) hi = mid;
else lo = mid + 1;
}
return static_cast<int>(lo);
}Complexity summary
| Approach | Time | Extra space |
|---|---|---|
| Try every set of cut positions | O(C(n - 1, k - 1) · n) | O(k) |
| Partition DP | O(k · n²) | O(k · n), or O(n) with two rows |
| Binary search plus greedy check | O(n log S) | O(1) |
Note the condition the fast version depends on: non-negative numbers. With negatives, a longer piece can have a smaller sum, the greedy count stops being optimal, and the DP is the safe choice. Saying this without being asked shows you know why the trick works, not only that it does.
Edge cases
- k = 1: the answer is the total.
- k = n: every element is its own piece, so the answer is the largest element.
- Zeros, which make several splits tie and must not confuse the piece counter.
- One huge element among small ones: when k is large enough, the lower bound max(nums) is already the answer.
- Totals that overflow a 32-bit int in languages with fixed-width integers.
Mistakes
- Starting the search at 0 or 1 instead of max(nums), which lets the check accept limits smaller than an element.
- Writing the check as parts == k instead of parts <= k, which rejects valid limits.
- Using while lo <= hi with hi = mid, which can loop forever.
- Starting the count at 0 pieces instead of 1, so the last piece is never counted.
- Claiming the binary search works with negative numbers.
How to talk through it
Fictional example
- Candidate
- A direct DP works: best of j pieces over the first i numbers, trying every place for the last cut. That's k times n squared.
- Interviewer
- Can you do better?
- Candidate
- If I guess the answer is L, I can check it in one pass: fill each piece greedily and count pieces. A bigger L never needs more pieces, so I can binary search L between the biggest element and the total.
- Candidate
- Fewer than k pieces is still fine, since the numbers are non-negative and I can split a piece without raising any sum. That's n log of the total.
Related problems
Capacity to Ship Packages Within D Days is this problem with a different story, and its page spends more time on the binary search template itself. Find K Closest Elements binary searches a window start instead of a value. Dungeon Game can also be solved by searching a starting value, and Swim in Rising Water does it on a grid.
Rehearsing this one with Natively
The proof that the greedy check is optimal is where answers often go vague, so it is the part to practise. During a practice run on Mac or Windows, Natively can read this problem from a screenshot and put an approach and code in its overlay; comparing it with your DP and search is a good way to spot a missing bound. When you rehearse the explanation aloud in a mock interview, its transcript lets you reread how you justified "at most k". Details are on the AI interview assistant page.
Questions people ask
How do you solve Split Array Largest Sum?
Binary search the answer between max(nums) and sum(nums). For each candidate limit, greedily count how many pieces you need so that no piece exceeds it; the smallest limit that needs at most k pieces is the answer.
What is the time complexity of Split Array Largest Sum?
O(n log S) for the binary search version, where S is the sum of the array, with O(1) extra space. The partition DP is O(k · n²).
Why is the greedy check in Split Array Largest Sum correct?
Filling each piece as far as the limit allows never ends a piece earlier than any other valid split would, so it uses the fewest pieces. With non-negative numbers, fewer than k pieces can always be split further.
Does Split Array Largest Sum work with negative numbers?
The binary search with a greedy check relies on non-negative values. With negatives, use the partition DP.
Where to go next
Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.
Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.
