Skip to content

Commit e35eeaa

Browse files
authored
Merge pull request neetcode-gh#2643 from aadil42/patch-67
2 parents aea3459 + d011e91 commit e35eeaa

File tree

1 file changed

+41
-0
lines changed

1 file changed

+41
-0
lines changed
Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
/**
2+
* https://leetcode.com/problems/split-array-largest-sum/
3+
*
4+
* Binary Search
5+
* Time O(log(s)*n) (s = difference between the least and max possible value) | Space O(1)
6+
* @param {number[]} nums
7+
* @param {number} k
8+
* @return {number}
9+
*/
10+
var splitArray = function(nums, k) {
11+
12+
let left = Math.max(...nums);
13+
let right = nums.reduce((acc, num) => acc + num, 0);
14+
let result = right;
15+
while(left <= right) {
16+
const mid = (left + right) >> 1;
17+
if(canSplit(mid)) {
18+
result = mid;
19+
right = mid - 1;
20+
} else {
21+
left = mid + 1;
22+
}
23+
}
24+
25+
function canSplit(largest) {
26+
let splitCount = 0;
27+
let currSum = 0;
28+
29+
for(let i = 0; i < nums.length; i++) {
30+
currSum += nums[i];
31+
if(currSum > largest) {
32+
currSum = nums[i];
33+
splitCount++;
34+
}
35+
}
36+
37+
return splitCount + 1 <= k;
38+
}
39+
40+
return result;
41+
};

0 commit comments

Comments
 (0)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy