Binary search + greedy check
Time O(n log(sum)) Space O(1)parts(limit): start a new part whenever adding the next number would exceed the limit. Find the smallest limit with parts ≤ k.
nums = [7,2,5,10,8], k = 2range(vars)
Step 1/5No piece can be smaller than the biggest number (10) and one piece holds everything (32). The answer is in [10, 32].
class Solution {
public int splitArray(int[] nums, int k) {
long lo = 0, hi = 0;
for (int x : nums) { lo = Math.max(lo, x); hi += x; }
while (lo < hi) {
long mid = (lo + hi) / 2;
if (parts(nums, mid) <= k) hi = mid; else lo = mid + 1;
}
return (int) lo;
}
private int parts(int[] nums, long limit) {
int count = 1;
long run = 0;
for (int x : nums) {
if (run + x > limit) { count++; run = 0; }
run += x;
}
return count;
}
}Verdict: Much simpler and faster than the O(k n²) DP.