logoNEURAL COOK
SearchAll PostsTagsNotesAuthor
logoNEURAL COOK

A posts created with Next.js and Tailwind.css

Explore

  • All posts
  • Notes
  • Snippets
  • Tags
  • RSS feed

Connect

instagramtwitterfacebookyoutubelinkedinmailgithub

© 2026 VIKI. All rights reserved.

Built with
Contents
Table Of Contents
Aggressive CowsAllocate BooksFind Peak ElementKth Element Of 2 Sorted ArraysMinimise Max Distance to Gas StationsSplit Array - Largest Sum
Code Scratch/take u forward/binary search/faqs

Split Array - Largest Sum

4 min read
On this pageQuestion
QuestionSolutionPatternHow to IdentifyDescriptionThe IntuitionComplexityCodeCaveatsConcepts to Think AboutLogical Follow-up

# Question

Given an integer array aaa of size nnn and an integer kkk. We need to split the array into kkk non-empty contiguous subarrays. The goal is to minimize the largest sum among these kkk subarrays.

Return the value xxx, where xxx is the minimum possible "maximum subarray sum."

# Solution

# Pattern

Binary Search on Answer Space When the problem asks to "Minimize the Maximum" or "Maximize the Minimum" of a value, and the possibility of achieving that value is monotonic (if xxx works, x+1x+1x+1 also works), we binary search the answer directly.

# How to Identify

  • Optimization Goal: Keywords like "minimized largest" or "maximized smallest."
  • Contiguous Constraints: The splits must be in order (subarrays, not subsets).
  • Feasibility Check: It is easy (O(n)O(n)O(n)) to check if a specific "max sum" can be achieved using kkk or fewer splits.

# Description

Step-by-step explanation:

  • Define the Search Space:
    • The minimum possible "largest sum" is the value of the largest element in the array (low=max⁡(a)low = \max(a)low=max(a)).
    • The maximum possible "largest sum" is the sum of all elements (high=∑ahigh = \sum ahigh=∑a).
  • The Binary Search:
    • Pick a middle value mid from the range [low,high][low, high][low,high].
    • Treat mid as the maximum capacity allowed for any subarray.
  • Greedy Validation (The Predicate):
    • Iterate through the array and accumulate a current sum.
    • If adding the next element exceeds mid, start a new subarray (increment count) and reset the current sum to that element.
  • Decision Choice:
    • If the number of subarrays required is ≤k\le k≤k, then mid is a potential answer. Try smaller values (high=mid−1high = mid - 1high=mid−1).
    • If we need more than kkk subarrays, mid is too small. Try larger values (low=mid+1low = mid + 1low=mid+1).

# The Intuition

Imagine you have a series of boxes and you want to pack them into kkk trucks. You want to make sure the heaviest truck is as light as possible.

  • If you set a weight limit too low, you will need more than kkk trucks.
  • If you set it very high, you only need 1 truck, but it will be very heavy. We use Binary Search to find the "sweet spot"—the lowest weight limit that still allows us to use exactly kkk (or fewer) trucks.

# Complexity

LabelWorstAverage
Time ComplexityO(n⋅log⁡(∑a−max⁡a))O(n \cdot \log(\sum a - \max a))O(n⋅log(∑a−maxa))O(n⋅log⁡(∑a−max⁡a))O(n \cdot \log(\sum a - \max a))O(n⋅log(∑a−maxa))
Space ComplexityO(1)O(1)O(1)O(1)O(1)O(1)

# Time Complexity

The search space is the sum of the array. Binary search takes log⁡(Sum)\log(Sum)log(Sum) steps. In each step, we traverse the array once (O(n)O(n)O(n)). Total time: O(n⋅log⁡(Sum))O(n \cdot \log(Sum))O(n⋅log(Sum)).

# Space Complexity

Only a constant amount of extra space is used for pointers and sum variables. No recursion stack is involved.

# Code

class Solution {
    public int largestSubarraySumMinimized(int[] a, int k) {
        // Range: [max element, total sum]
        long low = 0;
        long high = 0;
        for (int num : a) {
            low = Math.max(low, num);
            high += num;
        }
 
        long ans = high;
        while (low <= high) {
            long mid = low + (high - low) / 2;
            
            if (getRequiredSubarrays(a, mid) <= k) {
                ans = mid;
                high = mid - 1; // Try to minimize the maximum further
            } else {
                low = mid + 1; // Limit too small, need more capacity
            }
        }
        return (int) ans;
    }
 
    private int getRequiredSubarrays(int[] a, long limit) {
        int count = 1; // Start with the first subarray
        long currentSum = 0;
 
        for (int num : a) {
            if (currentSum + num > limit) {
                // Cannot fit in current subarray, start a new one
                count++;
                currentSum = num;
            } else {
                currentSum += num;
            }
        }
        return count;
    }
}

# Caveats

  • Integer Overflow: The sum of elements can easily exceed 231−12^{31}-1231−1. Always use long for low, high, and mid.
  • k > n: If kkk is greater than the number of elements, it's impossible to split into kkk non-empty subarrays. Your code should handle this (usually returns -1 or based on problem specs).
  • Non-positive values: If the array has negative numbers, the greedy check fails because the sum is no longer monotonic.

# Concepts to Think About

  • Binary Search on Answer: This is a meta-pattern. You aren't searching the input; you're searching the solution space.
  • Greedy + BS: Notice how the problem combines two paradigms.
  • Related Problems: - Capacity to Ship Packages Within D Days
    • Koko Eating Bananas
    • Book Allocation Problem
    • Painter's Partition Problem

# Logical Follow-up

Question: What if the order of elements can be changed? (Subsets instead of Subarrays) Solution: The problem becomes NP-Hard (equivalent to the Bin Packing problem or Partition problem). You would need to use Backtracking or Dynamic Programming with Bitmasking, which only works for very small nnn (usually n < 20).

Question: How would you modify this to find the split points? Solution: Once you find the optimal mid, run the getRequiredSubarrays logic one last time and record the indices where currentSum + num > limit occurs.

←PreviousMinimise Max Distance to Gas StationsNext→Lower Bound

On this page

QuestionSolutionPatternHow to IdentifyDescriptionThe IntuitionComplexityCodeCaveatsConcepts to Think AboutLogical Follow-up