Split Array Largest Sum

Partition the array into m contiguous parts minimizing the maximum part sum — binary search on the answer.

Hard
Time O(n log S) Space O(1)
LeetCode
4 min read
binary-search greedy

Problem#

Split nums into k non-empty contiguous parts. Minimize the largest part sum.

Examples#

  • nums = [7,2,5,10,8], k = 218
  • nums = [1,2,3,4,5], k = 29

Constraints#

  • 1 <= n <= 1000.

Hints#

Hint 1
Binary search on the answer value. For a candidate cap, count how many parts are needed using greedy splits.

Approach#

Binary search on the answer in [max(nums), sum(nums)]. Predicate: “can we split into ≤ k parts with each ≤ cap?” — greedy left-to-right counting.

Solution#

Split Array Largest Sum
class Solution {
public:
int splitArray(vector<int>& nums, int k) {
long long lo = *max_element(nums.begin(), nums.end());
long long hi = accumulate(nums.begin(), nums.end(), 0LL);
auto canDo = [&](long long cap) {
int parts = 1; long long cur = 0;
for (int x : nums) {
if (cur + x > cap) { ++parts; cur = x; }
else cur += x;
}
return parts <= k;
};
while (lo < hi) {
long long mid = lo + (hi - lo) / 2;
if (canDo(mid)) hi = mid;
else lo = mid + 1;
}
return (int)lo;
}
};

Editorial#

Two ideas: the answer lies in [max, sum], and the predicate “can be done with ≤ k parts” is monotone in cap (more cap → fewer parts). Binary search on cap converges to the smallest cap that still admits a valid split.

Complexity#

  • Time: O(n log S).
  • Space: O(1).

Concept revision#

Search ESC

Keyboard shortcuts

Shortcuts are disabled while typing in inputs.