Search for a command to run...
Largest minimum gap that still fits every cow
Initialization
Sorted first: 0, 3, 4, 7, 10, 9 → 0, 3, 4, 7, 9, 10. Ask "can the cows be placed at least d apart?" — if d works, every smaller gap works too, so the answers are monotonic and the largest workable d can be binary searched.
Binary Search on the Answer
1function canWePlace(nums, dist, cows) {2 const n = nums.length;3 let cntCows = 1;4 let last = nums[0];5 6 for (let i = 1; i < n; i++) {7 // Far enough from the last cow — place one here8 if (nums[i] - last >= dist) {9 cntCows++;10 last = nums[i];11 }12 if (cntCows >= cows) return true;13 }14 return false;//low: 1high: 1015}16 17function aggressiveCows(nums, k) {18 const n = nums.length;19 nums.sort((a, b) => a - b);20 21 let low = 1, high = nums[n - 1] - nums[0];22 23 while (low <= high) {24 const mid = Math.floor((low + high) / 2);25 26 // This gap works — try a bigger one27 if (canWePlace(nums, mid, k)) {28 low = mid + 1;29 } else {30 high = mid - 1;31 }32 }33 return high;34}