-
Notifications
You must be signed in to change notification settings - Fork 1
/
13th_december.java
34 lines (32 loc) · 1000 Bytes
/
13th_december.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
static int splitArray(int[] arr , int N, int K) {
// code here
int totalSum =0,max=Integer.MIN_VALUE;
for(int a : arr) {
totalSum+=a;
max = Math.max(max,a);
}
int lo=max,hi=totalSum,ans=Integer.MAX_VALUE;
while(lo<=hi) {
int mid = lo+(hi-lo)/2;
if(isValid(arr,mid,K)) {
ans=Math.min(ans,mid);
hi=mid-1; // To minimize our answer
} else {
lo=mid+1; // To get Valid Range
}
}
return ans;
}
// to check if requiredSum is possible to get by splitting array in k or less then k subarray
public static boolean isValid(int[] arr,int requiredSum,int k) {
int sum=0,count=1;
for(int a : arr) {
if(sum+a<=requiredSum) {
sum+=a;
} else {
sum=a;
count++;
}
}
return count<=k;
}