TLE error in aggressive cow problem

#include
using namespace std;
int n,c;
int check(int num,int stalls[])
{

int cows=1,pos=stalls[0];
for(int i=1;i<n;i++)
{
	if(stalls[i]-pos>=num)
	{
		pos=stalls[i];
		cows++;
		if(cows==c)
		return 1;
	}
}
return 0;

}

int bsearch(int arr[])
{

int s=0,e=n-1,max=-1;
while(s<=e)
{
int mid=(s+e)/2;

if(check(mid,arr)==1)

{
if(mid>max)
max=mid;
s=mid+1;
}
else
e=mid;

}
return max;

}

int main() {

cin>>n>>c;
int a[n];
for(int i=0;i<n;i++)
cin>>a[i];

cout<<bsearch(a);
return 0;
}

Hi, your code logic is fine but there are somethings u missed

  1. your end value should be (arr[n-1]-arr[0]) instead of n-1 as arr[n-1]-arr[0] will be the maximum spacing the cows can have and your answer will lie between 0 and arr[n-1]-arr[0]
  2. you need to sort the array as indexing has to be from lower value to higher value

here 's the updated code : https://ide.codingblocks.com/s/184621

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.