AggressiveCows
- Place cows in stalls such that, the minimum distance between two cows is maximum.
- The minimum answer will always be 1 (low)
- The maximum answer will always be last_stall - first_stall (high) considering 2 cows are there.
isPossible
checks in linear time if current_distance is possible for given number of cows
aggressiveCows
calls isPossible using binary search by eliminating half of probable search space on every iteration.
bool isPossible(vector<int>& arr, int dist, int cows) {
int last = arr[0];
cows--;
for (int i = 1; i < arr.size() && cows > 0; i++) {
if (arr[i] - last >= dist) {
last = arr[i];
cows--;
}
}
if(cows > 0)
return false;
return true;
}
int aggressiveCows(vector<int> &stalls, int k)
{
sort(stalls.begin(), stalls.end());
int low = 1;
int high = stalls[stalls.size()-1] - stalls[0];
while (low <= high) {
int mid = low + (high-low)/2;
if(isPossible(stalls, mid, k)){
low = mid+1;
} else {
high = mid-1;
}
}
return high;
}