I wrote this program for book allocation challenge:-
import java.util.Scanner;
public class Main {
public static boolean valid(int[] arr,int n,int m,int ans){
int students=1;
int currentpages=0;
for(int i=0;i<n;i++){
if(currentpages+arr[i]>ans){
currentpages=arr[i];
students++;
if(students>m){
return false;
}
}else{
currentpages+=arr[i];
}
}
return true;
}
public static int bookallocation(int[] arr,int n,int m){
int totalpages=0;
int s=0,e=0;
for(int i=0;i<n;i++){
totalpages+=arr[i];
}
s=arr[n-1];
e=totalpages;
int finalans=s;
while(s<=e){
int mid=(s+e)/2;
if(valid(arr,n,m,mid)){
finalans=mid;
e=mid-1;
}else{
s=mid+1;
}
}
return finalans;
}
public static void main(String args[]) {
Scanner scn = new Scanner(System.in);
int t = scn.nextInt();
for(int i=1;i<=t;i++){
int n = scn.nextInt();
int m = scn.nextInt();
int[] arr = new int[n];
for(int j=0;j<n;j++)
arr[i] = scn.nextInt();
System.out.println(bookallocation(arr,n,m));
}
}
}
And the input was this :-
1
4 2
12 34 67 90
Now,my output is coming out to be 90. But,I want my output to be 113 as required.