MCPcopy Create free account
hub / github.com/neetcode-gh/leetcode / splitArray

Function splitArray

javascript/0410-split-array-largest-sum.js:10–40  ·  view source on GitHub ↗
(nums, k)

Source from the content-addressed store, hash-verified

8 * @return {number}
9 */
10var splitArray = function (nums, k) {
11 let left = Math.max(...nums);
12 let right = nums.reduce((acc, num) => acc + num, 0);
13 let result = right;
14 while (left <= right) {
15 const mid = (left + right) >> 1;
16 if (canSplit(mid)) {
17 result = mid;
18 right = mid - 1;
19 } else {
20 left = mid + 1;
21 }
22 }
23
24 function canSplit(largest) {
25 let splitCount = 0;
26 let currSum = 0;
27
28 for (let i = 0; i < nums.length; i++) {
29 currSum += nums[i];
30 if (currSum > largest) {
31 currSum = nums[i];
32 splitCount++;
33 }
34 }
35
36 return splitCount + 1 <= k;
37 }
38
39 return result;
40};

Callers

nothing calls this directly

Calls 1

canSplitFunction · 0.85

Tested by

no test coverage detected