Aggressive Cows

Last Updated : 14 Jul, 2026

Given an integer array arr[], which denotes the positions of stalls. All the positions are distinct. There are k aggressive cows.

Assign the cows to the stalls such that the minimum distance between any two cows is maximized.

Examples: 

Input: arr[] = [1, 2, 4, 8, 9], k = 3
Output: 3
Explanation: The first cow can be placed at arr[0], the second at arr[2], and the third at arr[3]. The minimum distance between any two cows is 3 (between arr[0] and arr[2]), which is the maximum possible among all valid arrangements

Input: arr[] = [10, 1, 2, 7, 5], k = 3
Output: 4
Explanation: The first cow can be placed at arr[0], the second at arr[1], and the third at arr[4]. In this arrangement, the minimum distance between any two cows is 4 (between arr[1] and arr[4]), which is the maximum possible among all valid arrangements.

Try It Yourself
redirect icon

[Naive Approach] By iterating over all possible distances

The idea is to place k cows such that the minimum distance between any two is maximized. We sort the array and try all possible distances from 1 to the maximum gap between stalls.
For each distance, we check if cows can be placed by assigning the first cow to the first stall, and placing the next cow only if the gap from the last placed cow is at least that distance.
If placement is possible, we update our answer; the largest such distance is returned.

C++
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

bool check(vector<int> &arr, int k, int dist) {
    
    // Place first cow at 0th index
    int cnt = 1;
    int prev = arr[0];

    for (int i = 1; i < arr.size(); i++) {
        
        // If the current stall is at least dist away
        // from the previous one place the cow here
        if (arr[i] - prev >= dist) {
            prev = arr[i];
            cnt++;
        }
    }

    // Return true if we are able to place all 'k' cows
    return (cnt >= k);
}

int aggressiveCows(vector<int> &arr, int k) {
  
    // sorting the array to ensure stalls in sequence
    sort(arr.begin(), arr.end());
    int res = 0;

    // Minimum and maximum possible minimum distance
    // between two stalls
    int minDist = 1;
    int maxDist = arr.back() - arr[0];

    // Iterating through all possible distances
    for (int i = minDist; i <= maxDist; i++) {

        // If we can place k cows with the
        // current distance i, update the res
        if (check(arr, k, i))
            res = i;
    }

    return res;
}

int main() {
    vector<int> arr = {1, 2, 4, 8, 9};
    int k = 3;

    int ans = aggressiveCows(arr, k);
    cout << ans;

    return 0;
}
C
#include <stdio.h>
#include <stdlib.h>

int compare(const void *a, const void *b) {
    return (*(int*)a - *(int*)b);
}

int check(int arr[], int size, int k, int dist) {

    // Place first cow at 0th index
    int cnt = 1;
    int prev = arr[0];

    for (int i = 1; i < size; i++) {

        // If the current stall is at least dist away
        // from the previous one place the cow here
        if (arr[i] - prev >= dist) {
            prev = arr[i];
            cnt++;
        }
    }

    // Return true if we are able to place all 'k' cows
    return (cnt >= k);
}

int aggressiveCows(int arr[], int size, int k) {

    // sorting the array to ensure stalls in sequence
    qsort(arr, size, sizeof(int), compare);
    int res = 0;

    // Minimum and maximum possible minimum distance
    // between two stalls
    int minDist = 1;
    int maxDist = arr[size - 1] - arr[0];

    // Iterating through all possible distances
    for (int i = minDist; i <= maxDist; i++) {

        // If we can place k cows with the
        // current distance i, update the res
        if (check(arr, size, k, i))
            res = i;
    }

    return res;
}

int main() {
    int arr[] = {1, 2, 4, 8, 9};
    int k = 3;
    int size = sizeof(arr) / sizeof(arr[0]);

    int ans = aggressiveCows(arr, size, k);
    printf("%d\n", ans);

    return 0;
}
Java
import java.util.Arrays;

class GFG {

    static boolean check(int[] arr, int k, int dist) {

        // Place first cow at 0th index
        int cnt = 1;
        int prev = arr[0];

        for (int i = 1; i < arr.length; i++) {

            // If the current stall is at least dist away
            // from the previous one place the cow here
            if (arr[i] - prev >= dist) {
                prev = arr[i];
                cnt++;
            }
        }

        // Return true if we are able to place all 'k' cows
        return (cnt >= k);
    }

    static int aggressiveCows(int[] arr, int k) {

        // sorting the array to ensure stalls in sequence
        Arrays.sort(arr);
        int res = 0;

        // Minimum and maximum possible minimum distance
        // between two stalls
        int minDist = 1;
        int maxDist = arr[arr.length - 1] - arr[0];

        // Iterating through all possible distances
        for (int i = minDist; i <= maxDist; i++) {

            // If we can place k cows with the
            // current distance i, update the res
            if (check(arr, k, i))
                res = i;
        }

        return res;
    }

    public static void main(String[] args) {
        int[] arr = {1, 2, 4, 8, 9};
        int k = 3;

        int ans = aggressiveCows(arr, k);
        System.out.println(ans);
    }
}
Python
def check(arr, k, dist):

    # Place first cow at 0th index
    cnt = 1
    prev = arr[0]

    for i in range(1, len(arr)):

        # If the current stall is at least dist away
        # from the previous one place the cow here
        if arr[i] - prev >= dist:
            prev = arr[i]
            cnt += 1

    # Return true if we are able to place all 'k' cows
    return cnt >= k

def aggressiveCows(arr, k):

    # sorting the array to ensure stalls in sequence
    arr.sort()
    res = 0

    # Minimum and maximum possible minimum distance
    # between two stalls
    minDist = 1
    maxDist = arr[-1] - arr[0]

    # Iterating through all possible distances
    for i in range(minDist, maxDist + 1):

        # If we can place k cows with the
        # current distance i, update the res
        if check(arr, k, i):
            res = i

    return res

if __name__ == "__main__":
    arr = [1, 2, 4, 8, 9]
    k = 3

    ans = aggressiveCows(arr, k)
    print(ans)
C#
using System;

class GFG {

    static bool check(int[] arr, int k, int dist) {

        // Place first cow at 0th index
        int cnt = 1;
        int prev = arr[0];

        for (int i = 1; i < arr.Length; i++) {

            // If the current stall is at least dist away
            // from the previous one place the cow here
            if (arr[i] - prev >= dist) {
                prev = arr[i];
                cnt++;
            }
        }

        // Return true if we are able to place all 'k' cows
        return (cnt >= k);
    }

    static int aggressiveCows(int[] arr, int k) {

        // sorting the array to ensure stalls in sequence
        Array.Sort(arr);
        int res = 0;

        // Minimum and maximum possible minimum distance
        // between two stalls
        int minDist = 1;
        int maxDist = arr[arr.Length - 1] - arr[0];

        // Iterating through all possible distances
        for (int i = minDist; i <= maxDist; i++) {

            // If we can place k cows with the
            // current distance i, update the res
            if (check(arr, k, i))
                res = i;
        }

        return res;
    }

    static void Main() {
        int[] arr = {1, 2, 4, 8, 9};
        int k = 3;

        int ans = aggressiveCows(arr, k);
        Console.WriteLine(ans);
    }
}
JavaScript
function check(arr, k, dist) {

    // Place first cow at 0th index
    let cnt = 1;
    let prev = arr[0];

    for (let i = 1; i < arr.length; i++) {

        // If the current stall is at least dist away
        // from the previous one place the cow here
        if (arr[i] - prev >= dist) {
            prev = arr[i];
            cnt++;
        }
    }

    // Return true if we are able to place all 'k' cows
    return (cnt >= k);
}

function aggressiveCows(arr, k) {

    // sorting the array to ensure stalls in sequence
    arr.sort((a, b) => a - b);
    let res = 0;

    // Minimum and maximum possible minimum distance
    // between two stalls
    let minDist = 1;
    let maxDist = arr[arr.length - 1] - arr[0];

    // Iterating through all possible distances
    for (let i = minDist; i <= maxDist; i++) {

        // If we can place k cows with the
        // current distance i, update the res
        if (check(arr, k, i))
            res = i;
    }

    return res;
}

// Driver Code
let arr = [1, 2, 4, 8, 9];
let k = 3;

let ans = aggressiveCows(arr, k);
console.log(ans);

Output
3

Time Complexity: O(n × (max(arr) - min(arr))), where n is the size of the array, max(arr) is the maximum element in the array and min(arr) is minimum element in the array.
Auxiliary Space: O(1).

The minimum distance between cows follows a monotonic property, which makes binary search possible.

  • If we can place all cows with a minimum distance d, then placing them with any smaller distance is also possible because allowing smaller gaps gives us more flexibility and space to place cows closer together.
  • On the other hand, if we can’t place all cows with distance d, then any larger distance also won’t work—since increasing the gap makes placement even harder.

So, we apply binary search on the distance range to find the largest minimum distance possible.
To check if a distance works, we place the first cow at the first stall and place each next cow only if it’s at least d units away from the last one. If all cows fit, it’s a valid distance.

C++
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

bool check(vector<int> &arr, int k, int dist) {

    // place first cow at 0th index
    int cnt = 1;
    int prev = arr[0];

    for (int i = 1; i < arr.size(); i++) {

        // if the current stall is at least dist away
        // from the previous one place the cow here
        if (arr[i] - prev >= dist) {
            prev = arr[i];
            cnt++;
        }
    }

    // return true if we are able to place all 'k' cows
    return (cnt >= k);
}

int aggressiveCows(vector<int> &arr, int k) {

    // sorting the array to ensure stalls in sequence
    sort(arr.begin(), arr.end());
    int res = 0;

    // Search Space for Binary Search
    int lo = 1;
    int hi = arr.back() - arr[0];

    while(lo <= hi) {
        int mid = lo + (hi - lo) / 2;

        // If the mid ditance is possible, update
        // the result and search for larger ditance
        if(check(arr, k, mid)) {
            res = mid;
            lo = mid + 1;
        }
        else {
            hi = mid - 1;
        }
    }

    return res;
}

int main() {
    vector<int> arr = {1, 2, 4, 8, 9};
    int k = 3;

    int ans = aggressiveCows(arr, k);
    cout << ans;

    return 0;
}
C
#include <stdio.h>
#include <stdlib.h>

int compare(const void *a, const void *b) {
    return (*(int*)a - *(int*)b);
}

int check(int arr[], int n, int k, int dist) {

    // place first cow at 0th index
    int cnt = 1;
    int prev = arr[0];

    for (int i = 1; i < n; i++) {

        // if the current stall is at least dist away
        // from the previous one place the cow here
        if (arr[i] - prev >= dist) {
            prev = arr[i];
            cnt++;
        }
    }

    // return true if we are able to place all 'k' cows
    return (cnt >= k);
}

int aggressiveCows(int arr[], int n, int k) {

    // sorting the array to ensure stalls in sequence
    qsort(arr, n, sizeof(int), compare);
    int res = 0;

    // search Space for Binary Search
    int lo = 1;
    int hi = arr[n - 1] - arr[0];

    while(lo <= hi) {
        int mid = lo + (hi - lo) / 2;

        // If the mid distance is possible, update
        // the result and search for larger distance
        if(check(arr, n, k, mid)) {
            res = mid;
            lo = mid + 1;
        }
        else {
            hi = mid - 1;
        }
    }

    return res;
}

int main() {
    int arr[] = {1, 2, 4, 8, 9};
    int k = 3;
    int n = sizeof(arr) / sizeof(arr[0]);

    int ans = aggressiveCows(arr, n, k);
    printf("%d\n", ans);

    return 0;
}
Java
import java.util.Arrays;

class GFG {

    static boolean check(int[] arr, int k, int dist) {

        // place first cow at 0th index
        int cnt = 1;
        int prev = arr[0];

        for (int i = 1; i < arr.length; i++) {

            // if the current stall is at least dist away
            // from the previous one place the cow here
            if (arr[i] - prev >= dist) {
                prev = arr[i];
                cnt++;
            }
        }

        // return true if we are able to place all 'k' cows
        return (cnt >= k);
    }

    static int aggressiveCows(int[] arr, int k) {

        // sorting the array to ensure stalls in sequence
        Arrays.sort(arr);
        int res = 0;

        // Search Space for Binary Search
        int lo = 1;
        int hi = arr[arr.length - 1] - arr[0];

        while(lo <= hi) {
            int mid = lo + (hi - lo) / 2;

            // If the mid distance is possible, update
            // the result and search for larger distance
            if(check(arr, k, mid)) {
                res = mid;
                lo = mid + 1;
            }
            else {
                hi = mid - 1;
            }
        }

        return res;
    }

    public static void main(String[] args) {
        int[] arr = {1, 2, 4, 8, 9};
        int k = 3;

        int ans = aggressiveCows(arr, k);
        System.out.println(ans);
    }
}
Python
def check(arr, k, dist):

    # place first cow at 0th index
    cnt = 1
    prev = arr[0]

    for i in range(1, len(arr)):

        # if the current stall is at least dist away
        # from the previous one place the cow here
        if arr[i] - prev >= dist:
            prev = arr[i]
            cnt += 1

    # return true if we are able to place all 'k' cows
    return cnt >= k

def aggressiveCows(arr, k):

    # sorting the array to ensure stalls in sequence
    arr.sort()
    res = 0

    # search Space for Binary Search
    lo = 1
    hi = arr[-1] - arr[0]

    while lo <= hi:
        mid = lo + (hi - lo) // 2

        # If the mid distance is possible, update
        # the result and search for larger distance
        if check(arr, k, mid):
            res = mid
            lo = mid + 1
        else:
            hi = mid - 1

    return res

if __name__ == "__main__":
    arr = [1, 2, 4, 8, 9]
    k = 3

    ans = aggressiveCows(arr, k)
    print(ans)
C#
using System;

class GFG {

    static bool check(int[] arr, int k, int dist) {

        // place first cow at 0th index
        int cnt = 1;
        int prev = arr[0];

        for (int i = 1; i < arr.Length; i++) {

            // if the current stall is at least dist away
            // from the previous one place the cow here
            if (arr[i] - prev >= dist) {
                prev = arr[i];
                cnt++;
            }
        }

        // return true if we are able to place all 'k' cows
        return (cnt >= k);
    }

    static int aggressiveCows(int[] arr, int k) {

        // sorting the array to ensure stalls in sequence
        Array.Sort(arr);
        int res = 0;

        // search Space for Binary Search
        int lo = 1;
        int hi = arr[arr.Length - 1] - arr[0];

        while(lo <= hi) {
            int mid = lo + (hi - lo) / 2;

            // if the mid distance is possible, update
            // the result and search for larger distance
            if(check(arr, k, mid)) {
                res = mid;
                lo = mid + 1;
            }
            else {
                hi = mid - 1;
            }
        }

        return res;
    }

    static void Main() {
        int[] arr = {1, 2, 4, 8, 9};
        int k = 3;

        int ans = aggressiveCows(arr, k);
        Console.WriteLine(ans);
    }
}
JavaScript
function check(arr, k, dist) {

    // place first cow at 0th index
    let cnt = 1;
    let prev = arr[0];

    for (let i = 1; i < arr.length; i++) {

        // if the current stall is at least dist away
        // from the previous one place the cow here
        if (arr[i] - prev >= dist) {
            prev = arr[i];
            cnt++;
        }
    }

    // return true if we are able to place all 'k' cows
    return (cnt >= k);
}

function aggressiveCows(arr, k) {

    // sorting the array to ensure stalls in sequence
    arr.sort((a, b) => a - b);
    let res = 0;

    // search Space for Binary Search
    let lo = 1;
    let hi = arr[arr.length - 1] - arr[0];

    while (lo <= hi) {
        let mid = Math.floor(lo + (hi - lo) / 2);

        // if the mid distance is possible, update
        // the result and search for larger distance
        if (check(arr, k, mid)) {
            res = mid;
            lo = mid + 1;
        } else {
            hi = mid - 1;
        }
    }

    return res;
}

// Driver Code
const arr = [1, 2, 4, 8, 9];
const k = 3;

const ans = aggressiveCows(arr, k);
console.log(ans);

Output
3

Time Complexity: O(n log d), we first sort the array, which takes O(n log n) time. After that, we perform a binary search on the distance range, from 1 to the maximum possible distance between the farthest stalls, which gives us log d steps (where d = arr[n-1] - arr[0] or max(arr) - min(arr) ). For each distance in the binary search, we run the check() function to verify if cow placement is possible, which takes O(n) time in the worst case.
Auxiliary Space: O(1)

Comment