Aggressive cows problems

can u plzz tell if
5 stalls 3 cows
and index of stalls are 1,2,8,4,9

the answer should be 4;
but in sample output it is given 3…
so how come 3.?

@ynikhil1999
The answer is 3 only.
We can place the cows in two possible configurations -
1 , 4 , 8
1 , 4 , 9
These are the stall indices.

Both the configurations give the same answer i.e. 3 as 3 is the distance between Stall 1 and Stall 4. This is the largest possible minimum distance between any 2 cows.

I don’t understand how you are getting the answer 4.

i thought maximum gap is to be returned…i.e between 4 to 9 , gap of 4 blocks

can u send me the code for this…

#include
using namespace std;

int isValid(long *stalls,int n,int s,int current_ans){

int cow = 1;
int currently_alloted = stalls[0];

for(int i=1;i<n;i++){

if(stalls[i]-currently_alloted >= current_ans){
    cow++;
    if(cow==s){
        return 1;
    }
    currently_alloted = stalls[i];

}

}
return 0;

}

long minDist(long stalls[],int n,int k){

int s = stalls[0];
int e = stalls[n-1];

int ans = 0;
int mid = 0;
while(s+1<e){ //here if you take s<e, it will become an infinite loop once we reach the required answer.
mid = (s+e)/2;

if(isValid(stalls,n,k,mid)==1){
    s = mid;
}
else{
    e = mid;
}

}
return s;

}

//Now the isValid Function takes as input the the minimum distance (or the mid point), number of cows, the array of stall positions and size of the array

int main()
{
int n,c;
cin>>n>>c;

long stalls[n];
for(int i=0;i<n;i++)
cin>>stalls[i];

int anss=minDist(stalls,n,c);
cout<<anss<<endl;

}

my answer is wrong

@ynikhil1999
As specified by the problem , you have to compute the maximum smallest distance between the stalls.

No , I cannot provide you with the solution code however I can help you out by suggesting some modifications and changes to your code.

As for your code , you are using a modified Binary Search implementation. The first and foremost condition to use Binary Search is that the array must be sorted or else it simply wouldn’t work. So just sort the stalls array before passing it to the function and it should work fine.

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.