codejump
HardPro challengePythonJavaScriptTypeScript

Binary Search — Split Array Largest Sum

AlgorithmsBinary SearchBinary Search on AnswerGreedy

solve(nums, k) — split nums (non-negative integers) into k non-empty
contiguous subarrays so that the largest subarray sum is as small as possible.
Return that minimum possible largest sum. k is at most nums.length.

A dynamic programme works but costs O(n² · k). Binary search the answer instead: for a
candidate limit, greedily cut a new subarray whenever adding the next value would pass
the limit and count the pieces. If the limit needs k pieces or fewer it is feasible
(you can always split pieces further, because k <= nums.length).

Examples

solve([7,2,5,10,8], 2)  → 18    // [7,2,5] [10,8]
solve([1,2,3,4,5], 2)   → 9     // [1,2,3] [4,5]
solve([1,4,4], 3)       → 4

Sample tests

Test #1Classic example
Input: [[7,2,5,10,8],2]
Output: 18
Test #2Increasing values
Input: [[1,2,3,4,5],2]
Output: 9
Test #3One value per piece
Input: [[1,4,4],3]
Output: 4