sagelearnai

Split Array Largest Sum

Difficulty: Hard · Pattern: Binary Search · LeetCode #410

Split non-negative nums into k non-empty contiguous subarrays to minimize the largest subarray sum. Return that minimized largest sum.

Examples

text
nums = [7, 2, 5, 10, 8], k = 2  →  18    ([7,2,5] and [10,8])
nums = [1, 2, 3, 4, 5], k = 2   →  9

Hints

  1. Guess a cap S: can the array be split into ≤ k pieces with every piece sum ≤ S?
  2. Feasibility is monotonic in S. Binary search S in [max(nums), sum(nums)].

Approach

Identical structure to shipping packages: pieces(S) greedily extends the current piece until adding the next number would exceed S, then starts a new one. Find the smallest S with pieces(S) ≤ k. O(n log(sum)). (A DP solution is O(k·n²), much slower.)

Complexity

Time: O(n · log(sum)). Space: O(1).

Python solution
def splitArray(nums, k):
    def pieces(cap):
        cnt, cur = 1, 0
        for x in nums:
            if cur + x > cap:
                cnt += 1; cur = 0
            cur += x
        return cnt
    lo, hi = max(nums), sum(nums)
    while lo < hi:
        mid = (lo + hi) // 2
        if pieces(mid) <= k:
            hi = mid
        else:
            lo = mid + 1
    return lo
JavaScript solution
function splitArray(nums, k) {
  const pieces = (cap) => { let c = 1, cur = 0; for (const x of nums) { if (cur + x > cap) { c++; cur = 0; } cur += x; } return c; };
  let lo = Math.max(...nums), hi = nums.reduce((a, b) => a + b, 0);
  while (lo < hi) { const mid = Math.floor((lo + hi) / 2); if (pieces(mid) <= k) hi = mid; else lo = mid + 1; }
  return lo;
}