I am only getting 33% my some test cases are wrong but why?

import java.util.*;
public class Main {
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int[] arr = new int[n];
int l = sc.nextInt();
for(int i = 0; i< n; i++) {
arr[i] = sc.nextInt();
}
System.out.println(binarySearch(arr, n, l));

}
public static int binarySearch(int[] arr, int n, int l) {
	int sum =0;
	int hi;
	int lo = 0;
	int ans = -1;
	for(int i = 0; i< n; i++) {
		sum += arr[i];
		lo = Math.max(arr[i], lo);
	}
	hi = sum;
	
	while(hi >= lo) {
		int mid = hi+ (lo-hi)/2;
		if(isvalid(arr, mid, l)) {
			hi = mid - 1;
			ans = mid;			
		}
		else 
			lo = mid + 1;
		
	}
	return ans;
}
public static boolean isvalid(int[] arr, int mid, int l) {
	int nl = 1;
	int sum = 0;
	for(int i = 0; i< arr.length; i++) {
		sum += arr[i];
		if(sum > mid) {
			nl++;
			sum = arr[i];
			if(nl > l)
				return false; 
		}
	}
	return true;
}

}

Hey Ayush,
I went through your code and observed that:

  1. Your input format doesn’t matches with the expected input.
  2. In binarysearch: While calculating mid it should be lo+(hi-lo)/2;
  3. In isvalid: the input size can vary upto 10^8 thus we need to store the variables in Long to prevent Integer Overflow.
  4. In isvalid: You are directly adding the value in sum, what if we can’t add the element to the current sum. So for that we need to add a condition in isvalid:
   if(arr[i]+sum<=mid){
            sum += arr[i];
   }else { // (sum > mid)
  		nl++;
  		sum = arr[i]*1L;
            if(nl > l)
              return false; 
  	}

I have updated your code,
You can refer it for further aid (It is recommended to try solving the problem yourself first).

I hope I’ve cleared your doubt. I ask you to please rate your experience here
Your feedback is very important. It helps us improve our platform and hence provide you
the learning experience you deserve.

On the off chance, you still have some questions or not find the answers satisfactory, you may reopen
the doubt.