Skip to problem
←

Split Array Largest Sum

Hard 0 attempts

Split the array nums into exactly k nonempty contiguous subarrays, preserving the original element order and using every element once.

For each split, compute the sum of each subarray and take the largest sum. Return the smallest possible value of that largest sum. Return the value, not the partition itself. All input values are nonnegative, including possibly zero.

Function contract

Implement splitArray(nums, k).

Output: Return the smallest possible largest subarray sum across all splits into exactly k nonempty contiguous subarrays.

Example 1

Input
nums = [7,2,5,10,8]
k = 2
Output
18

Explanation: Split into [7,2,5] and [10,8]. Their sums are 14 and 18, so the largest is 18; no valid split has a smaller largest sum.

Example 2

Input
nums = [1,2,3]
k = 3
Output
3
Constraints
  • 1 <= nums.length <= 1000
  • 0 <= nums[i] <= 10^6
  • 1 <= k <= min(50, nums.length)

Binary Search on Answer

Search between the largest individual value and the sum of all values. For a candidate limit, greedily extend the current subarray until the next value would exceed the limit, then start a new subarray. Because values are nonnegative, this uses the fewest groups possible under that limit.

If at most k groups are needed, the limit is feasible: any group can be split further until there are exactly k nonempty groups, without increasing any sum. Feasibility is monotonic, so binary search finds the smallest limit.

javascript
function splitArray(nums, k) {
  let lo = Math.max(...nums), hi = nums.reduce((a,b)=>a+b,0);
  while (lo < hi) {
    const mid = Math.floor(lo + (hi-lo)/2);
    let splits = 1, sum = 0;
    for (const n of nums) { if (sum+n>mid) { splits++; sum=n; } else sum+=n; }
    if (splits <= k) hi = mid; else lo = mid+1;
  }
  return lo;
}

Time: O(n log(S + 1)), where S is the total sum | Space: O(1)

Loading discussion…

Saved in this browser only. Private to you.

JavaScript