-
Notifications
You must be signed in to change notification settings - Fork 61
Expand file tree
/
Copy path0410-split-array-largest-sum.js
More file actions
45 lines (40 loc) · 922 Bytes
/
0410-split-array-largest-sum.js
File metadata and controls
45 lines (40 loc) · 922 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
41
42
43
44
45
/**
* 410. Split Array Largest Sum
* https://leetcode.com/problems/split-array-largest-sum/
* Difficulty: Hard
*
* Given an integer array nums and an integer k, split nums into k non-empty subarrays
* such that the largest sum of any subarray is minimized.
*
* Return the minimized largest sum of the split.
*
* A subarray is a contiguous part of the array.
*/
/**
* @param {number[]} nums
* @param {number} k
* @return {number}
*/
var splitArray = function(nums, k) {
let left = Math.max(...nums);
let right = nums.reduce((a, b) => a + b);
while (left < right) {
const mid = Math.floor((left + right) / 2);
let count = 1;
let sum = 0;
for (const num of nums) {
if (sum + num <= mid) {
sum += num;
} else {
count++;
sum = num;
}
}
if (count > k) {
left = mid + 1;
} else {
right = mid;
}
}
return left;
};