here is the code:
There is some problem
@vketan182
For this problem, fix one cow at the first position and then move ahead.
So I have created a minimum Distance function which basically calculates a mid point and treats that as the minimum distance to place a cow. If we have a position greater than or equal to this distance, we fix the cow at that position.
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 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;
}
Now all you need to do is call the minDist function in your main. Hope this helps!!
can you explain this how
??
run that while loop for the case s=e , u will get the answer.
btw it is not necessary to follow the same implementation.
u can use s<=e but then u need to make other changes as well.
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.