I try this code using binary search but some of the test cases got failed. I am not able to find errors in my code
My code:
import java.util.*;
public class Main {
public static void main(String args[]) {
Scanner scn = new Scanner(System.in);
int numofpainter = scn.nextInt();
int numofboard = scn.nextInt();
int[] boards = new int[numofboard];
for(int i=0;i<boards.length;++i)
{
boards[i] = scn.nextInt();
}
Arrays.sort(boards);
int lo = boards[boards.length-1];
int hi = sum(boards);
int midtime =0;
int ans =0;
while(lo<=hi)
{
midtime = lo +((hi-lo)/2);
if(numofpaintersrequired(boards, midtime)<= numofpainter)
{
ans = midtime;
hi = midtime-1;
}else {
lo = midtime+1;
}
}
System.out.println(ans);
}
public static int sum(int[]boards)
{
int sum=0;
for(int i=0;i<boards.length;++i)
{
sum+=boards[i];
}
return sum;
}
public static int numofpaintersrequired(int[]board,int timegiven)
{int painter =1;
int timetakenbyonepainter =0;
for(int i=0;i<board.length;++i)
{
timetakenbyonepainter +=board[i];
if(timetakenbyonepainter>timegiven)
{
timetakenbyonepainter= board[i];
painter++;
}
}
return painter;
}
}