Skip to content

Commit b11a4f9

Browse files
authored
Update 410-split-array-largest-sum.js
1 parent 03ccae9 commit b11a4f9

File tree

1 file changed

+41
-0
lines changed

1 file changed

+41
-0
lines changed

410-split-array-largest-sum.js

+41
Original file line numberDiff line numberDiff line change
@@ -98,3 +98,44 @@ When Largest sum of sub-arrays is in range [6, 15], we can always find a way to
9898
However, when Largest sum of sub-arrays is in range [5, 5], there is no way to do this.
9999
This mapped this problem into the second sub-problem. Bool array B here is [5:false, 6:true, 7:true, 8:true, ..., 15:true]. We want to find the index i of the first true in B, which is the answer of this entire question, and by solving the first sub-problem, we have an API that can tell us given an i (Largest sum of sub-arrays), whether B[i] is true (whether we can find a way to cut A to satisfy the constraint).
100100
*/
101+
102+
103+
// another
104+
105+
/**
106+
* @param {number[]} nums
107+
* @param {number} m
108+
* @return {number}
109+
*/
110+
const splitArray = (nums, m) => {
111+
let max = -Infinity, sum = 0
112+
for(let num of nums) {
113+
sum += num
114+
max = Math.max(max, num)
115+
}
116+
if (m === 1) return sum
117+
let l = max, r = sum
118+
while(l < r) {
119+
let mid = l + ((r - l) >> 1)
120+
if(valid(mid, nums, m)) {
121+
r = mid
122+
} else {
123+
l = mid + 1
124+
}
125+
}
126+
return l
127+
}
128+
129+
function valid(target, nums, m) {
130+
let cnt = 1, sum = 0
131+
for(let num of nums) {
132+
sum += num
133+
if(sum > target) {
134+
cnt++
135+
sum = num
136+
if(cnt > m) return false
137+
}
138+
}
139+
140+
return true
141+
}

0 commit comments

Comments
 (0)