Aggressive cows

Farmer John has built a new long barn, with N stalls. Given an array of integers A of size N where each element of the array represents the location of the stall, and an integer B which represent the number of cows.

His cows don’t like this barn layout and become aggressive towards each other once put into a stall. To prevent the cows from hurting each other, John wants to assign the cows to the stalls, such that the minimum distance between any two of them is as large as possible. What is the largest minimum distance?

Input Format

The first argument given is the integer array A.
The second argument given is the integer B.

Output Format

Return the largest minimum distance possible among the cows.

Constraints

2 <= N <= 100000
0 <= A[i] <= 10^9
2 <= B <= N

For Example

Input 1:
    A = [1, 2, 3, 4, 5]
    B = 3
Output 1:
    2

Input 2:
    A = [5, 17, 100, 11]
    B = 2
Output 2:
    95
public class Solution {
    public boolean isPossible(int[] arr, int minDist, int cows) {
        int count = 1;
        // Placing 1st cow at 1st place
        long last_position = arr[0];

        for (int i = 1; i < arr.length; i++) {
            if (arr[i] - last_position >= minDist) {
                last_position = arr[i];
                count++;
            }
            if (count == cows)
                return true;
        }
        return false;
    }

    public int solve(int[] A, int B) {
        Arrays.sort(A);
        // Min distance between cows = 0
        int min = 0;
        int high = A[A.length - 1] - A[0];
        int ans = -1;
        // Max distance between cows
        while (min <= high) {
            // Mid represents the min distance between all the cows
            int mid = min + (high - min) / 2;
            if (isPossible(A, mid, B)) {
                ans = mid;
                min = mid + 1;
            } else
                high = mid - 1;
        }
        return ans;
    }
}

Last updated