Split Array Largest Sum

Pattern: Binary search on the answer

hard

Minimise the largest part sum. Guess a limit L, cut the array greedily whenever a part would pass L, and count the parts. A bigger limit needs fewer parts, so binary search the smallest L that needs at most k.

The problem

Split an array of whole numbers (zero or more) into k non-empty parts that keep their order. Return the smallest possible value of the largest part sum. For example, [7, 2, 5, 10, 8] with k = 2 gives 18, from [7, 2, 5] and [10, 8], and [1, 2, 3, 4, 5] with k = 2 gives 9.

The function name splitArray matches LeetCode. Use the link above for the exact statement and limits.

Think first

  • Fix a limit L. What is the fewest parts you need so that no part passes L?
  • If limit L needs at most k parts, what about L + 1?
  • What are the smallest and largest limits worth trying?

Hints

    Brute force, and why it fails

    Dynamic programming over "first i values in j parts" is O(n² k), and this guide uses it to check the answers. Binary search with the greedy check is O(n log sum).

    The key insight

    "Minimise the largest" becomes "is limit L enough?", which a greedy pass answers. Because a bigger limit only helps, the best limit is a binary search.

    Dry run

    70 
    21 
    52 
    103 
    84 

    nums = [7, 2, 5, 10, 8] and k = 2. The answer lies between the largest value, 10, and the total, 32.

    Step 1 of 4

    The plan

    lo = max(nums), hi = sum(nums)
    while lo < hi:
        mid = lo + (hi - lo) / 2
        if partsNeeded(mid) <= k: hi = mid
        else: lo = mid + 1
    return lo
    
    partsNeeded(L): parts = 1, sum = 0
        for each v: if sum + v > L: parts = parts + 1; sum = 0
                    sum = sum + v
        return parts
    

    Complexity

    Time
    O(n log sum)
    Space
    O(1)

    About log₂ sum guesses, each one pass.

    Edge cases

    • k = 1: the total sum.
    • k = n: the largest value.
    • Zeros in the array: they never force a new part, and they still fit with fewer than k parts.
    I've built my logic, show the code

    Java

    class Solution {
        public int splitArray(int[] nums, int k) {
            long lo = 0, hi = 0;
            for (int v : nums) { lo = Math.max(lo, v); hi += v; }   // largest single value .. whole sum
            while (lo < hi) {
                long mid = lo + (hi - lo) / 2;
                if (partsNeeded(nums, mid) <= k) hi = mid;   // a limit of mid needs at most k parts: try lower
                else lo = mid + 1;
            }
            return (int) lo;
        }
    
        private int partsNeeded(int[] nums, long limit) {
            int parts = 1;
            long sum = 0;
            for (int v : nums) {
                if (sum + v > limit) { parts++; sum = 0; }   // start a new part when this one would overflow
                sum += v;
            }
            return parts;
        }
    }

    C++

    class Solution {
    public:
        int splitArray(vector<int>& nums, int k) {
            long long lo = 0, hi = 0;
            for (int v : nums) { lo = max(lo, static_cast<long long>(v)); hi += v; }   // largest value .. whole sum
            while (lo < hi) {
                long long mid = lo + (hi - lo) / 2;
                if (partsNeeded(nums, mid) <= k) hi = mid;   // a limit of mid needs at most k parts: try lower
                else lo = mid + 1;
            }
            return static_cast<int>(lo);
        }
    
        int partsNeeded(vector<int>& nums, long long limit) {
            int parts = 1;
            long long sum = 0;
            for (int v : nums) {
                if (sum + v > limit) { parts++; sum = 0; }   // start a new part when this one would overflow
                sum += v;
            }
            return parts;
        }
    };

    Python

    class Solution:
        def splitArray(self, nums: list[int], k: int) -> int:
            lo, hi = max(nums), sum(nums)           # largest single value .. whole sum
            while lo < hi:
                mid = (lo + hi) // 2
                if self.parts_needed(nums, mid) <= k:
                    hi = mid                        # a limit of mid needs at most k parts: try lower
                else:
                    lo = mid + 1
            return lo
    
        def parts_needed(self, nums: list[int], limit: int) -> int:
            parts, total = 1, 0
            for v in nums:
                if total + v > limit:               # start a new part when this one would overflow
                    parts += 1
                    total = 0
                total += v
            return parts

    Common mistakes

    • Starting lo at 0 or 1, which allows limits smaller than one value and breaks the greedy.
    • Requiring exactly k parts from the greedy check.
    • Summing in 32 bits when the array is long and values are large.

    Similar problems