惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

爱范儿
爱范儿
T
The Blog of Author Tim Ferriss
G
Google Developers Blog
博客园_首页
博客园 - 【当耐特】
量子位
S
SegmentFault 最新的问题
B
Blog RSS Feed
酷 壳 – CoolShell
酷 壳 – CoolShell
V
Visual Studio Blog
T
Tailwind CSS Blog
阮一峰的网络日志
阮一峰的网络日志
V
V2EX
Y
Y Combinator Blog
博客园 - 聂微东
The Cloudflare Blog
小众软件
小众软件
J
Java Code Geeks
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
月光博客
月光博客
H
Help Net Security
Jina AI
Jina AI
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
宝玉的分享
宝玉的分享

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant
Aggressive Cows
Jaspreet singh · 2026-06-22 · via DEV Community

Jaspreet singh

Problem Statement

Given:

  • Positions of stalls
  • k cows

Place the cows in stalls such that:

Minimum distance between any two cows

is maximized.

Return the maximum possible minimum distance.


Brute Force Intuition

In an interview, you can explain it like this:

We can try every possible distance from 1 up to the maximum distance between stalls. For each distance, check whether all cows can be placed while maintaining at least that gap.

This works but is inefficient.

Complexity

  • Time Complexity: O(N × MaxDistance)
  • Space Complexity: O(1)

Brute Force Code

for(int dist = 1; dist <= maxDistance; dist++){

    if(canPlaceCows(dist)){
        answer = dist;
    }
}


Moving Towards the Optimal Approach

The important question becomes:

Can we place all cows
such that minimum distance = X ?

If yes:

Try a larger distance

If no:

Try a smaller distance

This monotonic behaviour is perfect for Binary Search.


Pattern Recognition

Whenever you see:

  • Maximize Minimum
  • Minimum Distance
  • Feasibility Check

Think:

Binary Search on Answer


Key Observation

Suppose:

Distance = 3

and we can successfully place all cows.

Then:

Distance = 2
Distance = 1

will also work.

Similarly:

If distance 5 fails,

6
7
8

will also fail.

This creates a monotonic search space.


Optimal Approach

Step 1

Sort the stalls.

Arrays.sort(stalls);


Step 2

Binary Search on distance.

Search Space:

low = 1

high = stalls[n-1] - stalls[0]


Step 3

Check feasibility.

Place first cow at:

First Stall

Then greedily place every next cow at the first stall satisfying:

currentPosition - previousPosition >= distance


Optimal Java Solution

class Solution {

    public static int aggressiveCows(int[] stalls,
                                     int k) {

        Arrays.sort(stalls);

        int low = 1;

        int high =
            stalls[stalls.length - 1]
            - stalls[0];

        while (low <= high) {

            int mid =
                low + (high - low) / 2;

            if (canPlace(stalls, k, mid)) {

                low = mid + 1;

            } else {

                high = mid - 1;
            }
        }

        return high;
    }

    private static boolean canPlace(int[] stalls,
                                    int cows,
                                    int distance) {

        int count = 1;

        int lastPlaced = stalls[0];

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

            if (stalls[i] - lastPlaced >= distance) {

                count++;

                lastPlaced = stalls[i];
            }
        }

        return count >= cows;
    }
}


Dry Run

Input

stalls = [1,2,4,8,9]

k = 3

After Sorting:

1 2 4 8 9


Iteration 1

low = 1
high = 8

mid = 4

Try placing cows:

Cow 1 -> 1

Cow 2 -> 8

Need distance >= 4

Only:

2 cows placed

Not Possible.

Move Left.

high = 3


Iteration 2

mid = 2

Place:

1
4
8

3 cows placed.

Possible.

Try Bigger Distance

low = 3


Iteration 3

mid = 3

Place:

1
4
8

3 cows placed.

Possible.

low = 4

Loop Ends.


Answer

3

Maximum minimum distance.


Why Binary Search Works?

If:

Distance = 3

works,

then:

1
2

will definitely work.

If:

Distance = 5

fails,

then:

6
7
8

will also fail.

This monotonic property makes Binary Search possible.


Complexity Analysis

Metric Complexity
Time Complexity O(N log(MaxDistance))
Space Complexity O(1)

Interview One-Liner

Binary search the minimum distance and greedily check whether all cows can be placed while maintaining that distance.


Pattern Learned

Maximize Minimum
+
Feasibility Check

=> Binary Search on Answer

Similar Problems

  • Aggressive Cows
  • Allocate Minimum Pages
  • Painter's Partition
  • Capacity To Ship Packages
  • Koko Eating Bananas
  • Minimum Days To Make Bouquets

Memory Trick

Think:

Can I place all cows
with minimum distance X ?

YES
→ Try Bigger Distance

NO
→ Try Smaller Distance

Mental Model

Minimize Maximum
→ Allocate Pages

Maximize Minimum
→ Aggressive Cows

Whenever you hear:

"Maximum possible minimum distance"

your brain should immediately think:

Binary Search on Answer + Greedy Placement 🚀