I am getting time limit error

I made some changes in your code… all the changes are in while loop of binary search… please have a look.

#include
#include
using namespace std;
bool isPossible(int page[100],int n,int m,int mid){

int studentUsed=1;
int pages_reading=0;
for(int i=0; i<n; i++){
	
	if(pages_reading+page[i]>mid){
		studentUsed++;

		pages_reading=page[i];
		if(studentUsed>m){
			return false;
		}
	}
	else{
		pages_reading+=page[i];
	}
}
return true;

}

int main(){

int t;
cin>>t;
for(int i=0; i<t; i++){
	int n,m;
	int sum=0;
	cin>>n>>m;
	int page[100];
	for(int j=0; j<n;j++){
		cin>>page[j];
	}
	sum=accumulate(page, page+n, sum);
	int s=page[n-1];
	int e=sum;
	int ans=1000000;
	while(s<=e){
		
		int mid=(s+e)/2;
		if(isPossible(page,n,m,mid)){
			ans=min(ans,mid);
			e=mid-1;
		}
		else{
			s=mid+1;
		}
	}
	
	cout<<ans<<endl;
}

return 0;

}

thanks

Now all test case are failed.

have you changed s=page[n-1], ans = 1000000, mid = (s+e)/2…
moreover there is no need of ans = min(ans,mid), just write ans = mid;

thanks

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.