class AggressiveCows {
constructor(stalls, cows) {
this.stalls = stalls.sort((a, b) => a - b);
this.cows = cows;
}
canPlace(distance) {
let count = 1; // place first cow at first stall
let lastPos = this.stalls[0];
for (let i = 1; i < this.stalls.length; i++) {
if (this.stalls[i] - lastPos >= distance) {
count++;
lastPos = this.stalls[i];
if (count === this.cows) return true;
}
}
return false;
}
maxMinDistance() {
let low = 1;
let high = this.stalls[this.stalls.length - 1] - this.stalls[0];
let result = 0;
while (low <= high) {
const mid = Math.floor((low + high) / 2);
if (this.canPlace(mid)) {
result = mid; // mid works, try bigger
low = mid + 1;
} else {
high = mid - 1; // mid too big, try smaller
}
}
return result;
}
}
// Driver code
const stalls = [1, 2, 4, 8, 9, 12];
const cows = 3;
const aggressiveCows = new AggressiveCows(stalls, cows);
console.log(aggressiveCows.maxMinDistance());this.stalls = stalls.sort((a, b) => a - b);
sort stalls to check distances in order
let count = 1; // place first cow at first stall
start placing first cow at first stall
if (this.stalls[i] - lastPos >= distance) {
check if current stall is far enough from last placed cow
if (count === this.cows) return true;
all cows placed successfully with given distance
binary search over possible distances
if (this.canPlace(mid)) {
if cows can be placed with mid distance, try bigger
if cannot place, try smaller distance