DEV Community

Prashant Mishra
Prashant Mishra

Posted on

Aggressive Cows

Aggressive cows

class Solution {
    public int aggressiveCows(int[] stalls, int k) {
        // code here
        Arrays.sort(stalls);//sorted will help us in getting the maxDistance as the stalls would be sorted as per the distance
        int min = 1;// the min distance between the stall would be 1
        int max = stalls[stalls.length-1] - stalls[0]; // this would be the max distance between the fardest stalls
        int result = Integer.MIN_VALUE;

        while(min<=max){
            int mid = (min+max)/2;
            if(isPossible(mid, stalls, k)){
                result = Math.max(result, mid);
                min = mid+1;
            }
            else{
                max = mid-1;
            }
        }
        return result;

    }

    public static boolean isPossible(int maxDistance, int stalls[], int k){
        int noOfCowsOnStall = 1;//first cow will always be on first stall t og
        //to get the min distance that could be maxinum
        int indexOfPreviousStall = 0;
        for(int i =1;i<stalls.length;i++){
            //the distance should be more than or atleast the maxDistance for maxDistance to be
            //a valid answer
            if(stalls[i]- stalls[indexOfPreviousStall]>=maxDistance){
                //cow can be placed here
                indexOfPreviousStall = i;
                noOfCowsOnStall+=1;
                if(noOfCowsOnStall>=k) break;
            }
        }
        return noOfCowsOnStall>=k;
    }
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)