Skip to content

Commit 304f1d1

Browse files
authored
Create 410-split-array-largest-sum.js
1 parent 33c2442 commit 304f1d1

File tree

1 file changed

+34
-0
lines changed

1 file changed

+34
-0
lines changed

410-split-array-largest-sum.js

+34
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
/**
2+
* @param {number[]} nums
3+
* @param {number} m
4+
* @return {number}
5+
*/
6+
function doable(nums, cuts, max) {
7+
let acc = 0
8+
for(let num of nums) {
9+
if(num > max) return false
10+
else if(acc + num <= max) acc += num
11+
else {
12+
--cuts;
13+
acc = num;
14+
if(cuts < 0) return false
15+
}
16+
}
17+
return true
18+
}
19+
20+
21+
function splitArray(nums, m) {
22+
let left = 0
23+
let right = 0
24+
for(let num of nums) {
25+
left = Math.max(left, num)
26+
right += num
27+
}
28+
while(left < right) {
29+
let mid = Math.floor(left + (right - left) / 2)
30+
if(doable(nums, m - 1, mid)) right = mid
31+
else left = mid + 1
32+
}
33+
return left
34+
}

0 commit comments

Comments
 (0)