This is my code . Can you tell me where did I go wrong in my logic ?
import java.util.*;
public class Main {
public static void main(String args[]) {
Scanner scan = new Scanner(System.in) ;
int t = scan.nextInt() ;
while(t -- > 0){
int n = scan.nextInt() ; // no of books
int k = scan.nextInt() ; // no of students
int[] arr = new int[n] ;
for(int i = 0 ; i < n ; i ++){
arr[i] = scan.nextInt() ;
}
System.out.println(BA(arr,n,k)) ;
}
}
public static int BA(int[] arr , int n , int k){
int low = arr[0] ;
int sum = 0 ;
for(int val : arr){
sum += val ;
}
int high = sum ;
int res = 0 ;
while(low < high){
int mid = (low+high)/2 ; // mid is donatind max no of pages
if(isValid(arr,mid,n,k)) {
res = mid ;
high = mid-1 ;
}
else{
low = mid + 1 ;
}
}
return res ;
}
public static boolean isValid(int[] arr , int mx , int n , int k){
int s = 1 ; // number of students
int sum = 0 ;
for(int i = 0 ; i < n ; i ++){
sum += arr[i] ;
if(sum > mx){
s ++ ;
sum = arr[i] ;
}
if(s > k){
return false ;
}
}
return s == k ;
}
}