File tree 1 file changed +41
-0
lines changed
1 file changed +41
-0
lines changed Original file line number Diff line number Diff line change
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
+ } ;
You can’t perform that action at this time.
0 commit comments