-
Notifications
You must be signed in to change notification settings - Fork 2.5k
Expand file tree
/
Copy path0410-split-array-largest-sum.js
More file actions
40 lines (36 loc) · 971 Bytes
/
0410-split-array-largest-sum.js
File metadata and controls
40 lines (36 loc) · 971 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
/**
* https://leetcode.com/problems/split-array-largest-sum/
*
* Binary Search
* Time O(log(s)*n) (s = difference between the least and max possible value) | Space O(1)
* @param {number[]} nums
* @param {number} k
* @return {number}
*/
var splitArray = function (nums, k) {
let left = Math.max(...nums);
let right = nums.reduce((acc, num) => acc + num, 0);
let result = right;
while (left <= right) {
const mid = (left + right) >> 1;
if (canSplit(mid)) {
result = mid;
right = mid - 1;
} else {
left = mid + 1;
}
}
function canSplit(largest) {
let splitCount = 0;
let currSum = 0;
for (let i = 0; i < nums.length; i++) {
currSum += nums[i];
if (currSum > largest) {
currSum = nums[i];
splitCount++;
}
}
return splitCount + 1 <= k;
}
return result;
};