0
0
DSA C++programming

Aggressive Cows Maximum Minimum Distance in DSA C++

Choose your learning style9 modes available
Mental Model
We want to place cows in stalls so that the smallest distance between any two cows is as large as possible.
Analogy: Imagine placing friends in seats along a bench so that everyone has the most personal space possible between them.
Stalls: [1] -> [2] -> [4] -> [8] -> [9]
Cows placed: C at some stalls with max minimum gap
Dry Run Walkthrough
Input: stalls: [1, 2, 4, 8, 9], cows: 3
Goal: Place 3 cows in stalls so that the minimum distance between any two cows is as large as possible
Step 1: Sort stalls and set search range for distance: low=1, high=8
Stalls sorted: 1 -> 2 -> 4 -> 8 -> 9
Search range: low=1, high=8
Why: We need sorted stalls to check distances and binary search the answer
Step 2: Check mid distance = (1+8)//2 = 4; try placing cows with at least 4 apart
Place first cow at 1
Next cow at 8 (distance 7 from 1, >=4), third cow at 9 (distance 1 from 8, too small)
Only 2 cows placed
Why: Distance 4 is too large to place all 3 cows
Step 3: Reduce high to mid-1 = 3; check mid = (1+3)//2 = 2
Place cows at 1, 4, 8 (distances 3 and 4, both >=2)
All 3 cows placed successfully
Why: Distance 2 is possible, try for bigger distance
Step 4: Increase low to mid+1 = 3; check mid = (3+3)//2 = 3
Place cows at 1, 4, 8 (distances 3 and 4, both >=3)
All 3 cows placed successfully
Why: Distance 3 is possible, try for bigger distance
Step 5: Increase low to mid+1 = 4; now low=4, high=3 so stop
Maximum minimum distance found is 3
Why: Search ends when low > high; last successful distance is answer
Result:
Maximum minimum distance = 3
Annotated Code
DSA C++
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

bool canPlaceCows(const vector<int>& stalls, int cows, int dist) {
    int count = 1; // place first cow at first stall
    int last_pos = stalls[0];
    for (int i = 1; i < stalls.size(); i++) {
        if (stalls[i] - last_pos >= dist) {
            count++;
            last_pos = stalls[i];
            if (count == cows) return true; // all cows placed
        }
    }
    return false; // not all cows placed
}

int aggressiveCowsMaxMinDist(vector<int>& stalls, int cows) {
    sort(stalls.begin(), stalls.end());
    int low = 1;
    int high = stalls.back() - stalls.front();
    int result = 0;
    while (low <= high) {
        int mid = low + (high - low) / 2;
        if (canPlaceCows(stalls, cows, mid)) {
            result = mid; // mid distance possible
            low = mid + 1; // try for bigger distance
        } else {
            high = mid - 1; // try smaller distance
        }
    }
    return result;
}

int main() {
    vector<int> stalls = {1, 2, 4, 8, 9};
    int cows = 3;
    int maxDist = aggressiveCowsMaxMinDist(stalls, cows);
    cout << "Maximum minimum distance = " << maxDist << endl;
    return 0;
}
sort(stalls.begin(), stalls.end());
sort stalls to check distances in order
while (low <= high) {
binary search over possible distances
int mid = low + (high - low) / 2;
check middle distance candidate
if (canPlaceCows(stalls, cows, mid)) {
if cows can be placed with at least mid distance
result = mid; low = mid + 1;
record mid as possible answer and try bigger distance
else { high = mid - 1; }
try smaller distance if mid not possible
int count = 1; int last_pos = stalls[0];
place first cow at first stall
if (stalls[i] - last_pos >= dist) { count++; last_pos = stalls[i]; }
place next cow if distance condition met
if (count == cows) return true;
all cows placed successfully
OutputSuccess
Maximum minimum distance = 3
Complexity Analysis
Time: O(n log d) because we binary search over distance range d and check placement in O(n)
Space: O(n) for storing stall positions
vs Alternative: Naive approach tries all distances linearly O(n*d), binary search reduces to O(n log d)
Edge Cases
Only one stall
Can place only one cow, max distance is 0
DSA C++
if (count == cows) return true;
Number of cows equals number of stalls
Cows must be placed in all stalls, min distance is minimum gap between adjacent stalls
DSA C++
if (stalls[i] - last_pos >= dist)
All stalls at same position
Max distance is 0 since all stalls overlap
DSA C++
int high = stalls.back() - stalls.front();
When to Use This Pattern
When asked to maximize minimum distance between placed items in sorted positions, use binary search on distance with a feasibility check.
Common Mistakes
Mistake: Not sorting stalls before binary search
Fix: Sort stalls first to ensure correct distance checks
Mistake: Using linear search instead of binary search for distance
Fix: Use binary search to efficiently find max minimum distance
Mistake: Placing cows without checking minimum distance properly
Fix: Check distance between last placed cow and current stall before placing
Summary
Find the largest minimum distance to place cows in stalls.
Use when you want to spread items evenly with maximum minimum gap.
Binary search on distance combined with a greedy placement check is the key.