-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path180. SplitArrayLargestSum.java
More file actions
47 lines (41 loc) · 1 KB
/
180. SplitArrayLargestSum.java
File metadata and controls
47 lines (41 loc) · 1 KB
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
46
47
class Solution {
public int splitArray(int[] arr, int k) {
int n = arr.length;
int sum = 0;
int max = Integer.MIN_VALUE;
for(int i=0; i<n; i++) {
sum += arr[i];
max = Math.max(max, arr[i]);
}
int ans = sum;
int high = sum;
int low = max;
while(low <= high){
int mid = low+(high-low)/2;
if(isPossible(arr, k, mid)) {
ans = mid;
high = mid-1;
}
else {
low = mid+1;
}
}
return ans;
}
boolean isPossible(int[] arr, int k, int mid) {
int count = 1;
int n = arr.length;
int sum = 0;
for(int i=0; i<n; i++) {
sum+=arr[i];
if(sum>mid) {
sum = arr[i];
count++;
}
}
if(count<=k) {
return true;
}
return false;
}
}