1. Lower bound
The largest sum is at least the biggest single element.
let lo = Math.max(...nums)Typorithm · hard
Step 1 of 8 · intro card
Binary Search on Answer
Binary search the largest allowed subarray sum; greedily count pieces, minimizing the cap that fits within m subarrays.
We want to split nums into m contiguous parts, minimizing the largest part's sum.
Binary search that largest sum between the biggest element and the total.
For a candidate cap, greedily count how many pieces it forces; if at most m, the cap is feasible — search lower.
Search the max-subarray-sum cap.
Greedily count pieces under the cap.
Feasible when pieces <= m.
function splitArray(nums, m) {
let lo = Math.max(...nums);
let hi = nums.reduce((a, b) => a + b, 0);
while (lo < hi) {
const mid = (lo + hi) >> 1;
let pieces = 1;
let sum = 0;
for (const num of nums) {
if (sum + num > mid) {
pieces += 1;
sum = 0;
}
sum += num;
}
if (pieces <= m) {
hi = mid;
} else {
lo = mid + 1;
}
}
return lo;
}Connect each part of the code to the concept before you type.
The largest sum is at least the biggest single element.
let lo = Math.max(...nums)Binary search the allowed maximum subarray sum.
const mid = (lo + hi) >> 1Start a new subarray when adding would exceed the cap.
if (sum + num > mid) {
pieces += 1;
sum = 0;
}If it splits into at most m parts, try a smaller cap.
if (pieces <= m) {
hi = mid;
}Read the concept map and follow the code breakdown.
Type the implementation, repair mistakes and work through every recall exercise.
Use the final check without hints; revisit weak concepts in short practice sessions.