Skip to content

Commit 5e89bbb

Browse files
committed
Add solution #410
1 parent a9630a2 commit 5e89bbb

File tree

2 files changed

+46
-0
lines changed

2 files changed

+46
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -327,6 +327,7 @@
327327
406|[Queue Reconstruction by Height](./0406-queue-reconstruction-by-height.js)|Medium|
328328
407|[Trapping Rain Water II](./0407-trapping-rain-water-ii.js)|Hard|
329329
409|[Longest Palindrome](./0409-longest-palindrome.js)|Easy|
330+
410|[Split Array Largest Sum](./0410-split-array-largest-sum.js)|Hard|
330331
412|[Fizz Buzz](./0412-fizz-buzz.js)|Easy|
331332
414|[Third Maximum Number](./0414-third-maximum-number.js)|Easy|
332333
415|[Add Strings](./0415-add-strings.js)|Easy|
Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
/**
2+
* 410. Split Array Largest Sum
3+
* https://leetcode.com/problems/split-array-largest-sum/
4+
* Difficulty: Hard
5+
*
6+
* Given an integer array nums and an integer k, split nums into k non-empty subarrays
7+
* such that the largest sum of any subarray is minimized.
8+
*
9+
* Return the minimized largest sum of the split.
10+
*
11+
* A subarray is a contiguous part of the array.
12+
*/
13+
14+
/**
15+
* @param {number[]} nums
16+
* @param {number} k
17+
* @return {number}
18+
*/
19+
var splitArray = function(nums, k) {
20+
let left = Math.max(...nums);
21+
let right = nums.reduce((a, b) => a + b);
22+
23+
while (left < right) {
24+
const mid = Math.floor((left + right) / 2);
25+
let count = 1;
26+
let sum = 0;
27+
28+
for (const num of nums) {
29+
if (sum + num <= mid) {
30+
sum += num;
31+
} else {
32+
count++;
33+
sum = num;
34+
}
35+
}
36+
37+
if (count > k) {
38+
left = mid + 1;
39+
} else {
40+
right = mid;
41+
}
42+
}
43+
44+
return left;
45+
};

0 commit comments

Comments
 (0)