01
Problem Statement
Given an integer array nums and an integer k, split nums into k non-empty contiguous subarrays. Minimize the largest sum among these k subarrays. Return that minimum possible largest sum.
- We must preserve order: each subarray is a contiguous block. The "largest sum" is the maximum of the
ksubarray sums. We want to choosek-1split points so that this maximum is as small as possible. - Binary search on the answer: the answer is in
[max(nums), sum(nums)]. For a candidatemaxSum, check if we can split into at mostksubarrays such that each has sum<= maxSum(greedy: fill each subarray until adding the next element would exceedmaxSum, then start a new one).
02
Key Observations
- possible(maxSum): Greedily form subarrays: start a new subarray when adding the next element would make the current sum exceed
maxSum. Count the number of subarrays. Ifcount <= k, we can achieve thatmaxSum(we might use fewer thanksubarrays). So ifpossible(mid), try smaller (high = mid); elselow = mid + 1. Returnlow. - Lower bound is
max(nums)(one element per subarray); upper bound issum(nums)(one subarray).
03
Approach
High-level: Binary search maxSum in [max(nums), sum(nums)]. For each mid, greedy: count how many subarrays we need so that each has sum <= mid. If count <= k, high = mid; else low = mid + 1. Return low.
Steps:
low = max(nums),high = sum(nums). Whilelow < high:mid = low + (high - low) / 2.count = 1,cur = 0; for eachxin nums: ifcur + x > midthencount++,cur = 0;cur += x. Ifcount <= k,high = mid; elselow = mid + 1.- Return
low.
04
Implementation
Java
public int splitArray(int[] nums, int k) {
long low = 0, high = 0;
for (int x : nums) { low = Math.max(low, x); high += x; }
while (low < high) {
long mid = low + (high - low) / 2;
int parts = 1;
long cur = 0;
for (int x : nums) {
if (cur + x > mid) { parts++; cur = 0; }
cur += x;
}
if (parts <= k) {
high = mid;
}
else {
low = mid + 1;
}
}
return (int) low;
}05
Test Cases
Example 1
Input
nums = [7,2,5,10,8], k = 2
Expected
18Explanation
Best split [7,2,5] and [10,8].
06
Complexity Analysis
- Time: O(n log(sum)).
- Space: O(1).
07
Follow-ups
- Same as capacity to ship: minimize maximum.