712207. Aggressive Cows

Medium

Aggressive Cows

Slug: aggressive-cows

Difficulty: Medium

Id: 712207

Topic Tags: Binary Search, Algorithms

Company Tags: None

Summary

The Aggressive Cows problem involves determining the maximum number of cows that can be placed in a field such that no two aggressive cows are placed together. The input consists of an array of integers representing the positions where the cows can be placed.

Detailed Explanation

To solve this problem, we need to sort the cow positions first and then iterate through the sorted array to find the maximum number of non-aggressive cow pairs.

Here's a step-by-step breakdown:

  1. Sort the input array in ascending order.
  2. Initialize two variables count and maxCount to store the current count and maximum count of non-aggressive cows, respectively.
  3. Iterate through the sorted array. For each pair of positions (i, i+1), check if the distance between them is greater than or equal to 2 (since aggressive cows must be separated by at least one space). If the condition is met, increment count.
  4. Update maxCount with the maximum value it has seen so far.
  5. Return maxCount as the result.

Time complexity: O(n log n) due to sorting, where n is the number of cow positions. Space complexity: O(1), as we only use a constant amount of space.

Optimized Solutions

Java

View on GeeksforGeeks
public class AggressiveCows {
    public static int aggressiveCows(int[] position) {
        Arrays.sort(position);
        int count = 0;
        int maxCount = 0;

        for (int i = 1; i < position.length; i++) {
            if (position[i] - position[i-1] >= 2) {
                count++;
            } else {
                count = 0;
            }
            maxCount = Math.max(maxCount, count);
        }

        return maxCount;
    }
}

DevExCode

Master coding interviews with Leetcode, system design, TechBit, QuickLearn, DevTips, Tech Battles, and career services.

© 2026 DevExCode. All rights reserved.