Hey , why is end = stalls[n-1]-stalls[0] it should [n-1] only
Aggressive cows
hello @soumyabhardwaj75
the first stall is present at stall[0]
the last stall is present at stall[n-1]
then what is maximum sepration possible between two cows?
it should be possible when we put one cow at stall[0] and othercow at stall[n-1]
and distance will be stall[n-1]-stall[0]
we have used int min_space but we haven’t provided any value to it
#include using namespace std; bool canPlaceCows(int stalls[], int n, int cows , int min_sep) { int last_cow = stalls[0]; // plpace last cow in the first stall int cnt = 1; for (int i = 0; i < n; i++) { if (stalls[i] - last_cow >= min_sep) { last_cow = stalls[i]; cnt++; if (cnt == cows) { return true; } } } return false; } int main () { int stalls[] = {1, 2, 4, 8, 9}; int n = 5; int cows = 3; // binary search algorithm int s = 0; int e = stalls[n - 1] - stalls[0]; int ans = 0; while (s <= e) { int mid = (s + e) / 2; bool cowRakhpaye = canPlaceCows(stalls, n, mid, cows); if (cowRakhpaye) { // agar cow rakh paye to usse bade space me try krenge ans = mid; s = mid + 1; } else { e = mid - 1; } } cout << ans << endl; return 0; }
min_step is argument of the function, we dont have to initialise /assign any value to it.
when we call the function while passing value then at that time min_step will get initialised by passed value
https://ide.codingblocks.com/s/466831 can u tell what’s the problem with this code ? it is not working properly
check now->
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.