-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy path410_Split Array Largest Sum.java
39 lines (36 loc) · 1.25 KB
/
410_Split Array Largest Sum.java
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
class Solution {
public int splitArray(int[] nums, int k) {
int start = 0;
int end = 0;
for (int i = 0; i < nums.length; i++) {
start = Math.max(start,nums[i]); // highest value in the array (maximum partition we can make => minmum Answer)
end += nums[i]; // sum of the array (if m is 1 => maximum Answer)
}
// binary search
while (start < end){
// try for the middle
int middle = start + (end - start) / 2;
// calculate in many pieces you can divide this with max sum
int sum = 0;
int pieces = 1;
for (int num: nums
) {
if (sum + num > middle) {
// cannot add more element in subArray, make new one
// can add this in new subArray ,then sum = num ( for new subArray )
sum = num;
pieces++;
} else {
// add elements together
sum += num;
}
}
if(pieces > k){
start = middle + 1;
} else {
end = middle;
}
}
return end; // here start = end
}
}