classSolution{publicintaggressiveCows(int[]stalls,intk){// code hereArrays.sort(stalls);//sorted will help us in getting the maxDistance as the stalls would be sorted as per the distanceintmin=1;// the min distance between the stall would be 1intmax=stalls[stalls.length-1]-stalls[0];// this would be the max distance between the fardest stallsintresult=Integer.MIN_VALUE;while(min<=max){intmid=(min+max)/2;if(isPossible(mid,stalls,k)){result=Math.max(result,mid);min=mid+1;}else{max=mid-1;}}returnresult;}publicstaticbooleanisPossible(intmaxDistance,intstalls[],intk){intnoOfCowsOnStall=1;//first cow will always be on first stall t og//to get the min distance that could be maxinumintindexOfPreviousStall=0;for(inti=1;i<stalls.length;i++){//the distance should be more than or atleast the maxDistance for maxDistance to be//a valid answerif(stalls[i]-stalls[indexOfPreviousStall]>=maxDistance){//cow can be placed hereindexOfPreviousStall=i;noOfCowsOnStall+=1;if(noOfCowsOnStall>=k)break;}}returnnoOfCowsOnStall>=k;}}
Top comments (0)
Subscribe
We're a place where coders share, stay up-to-date and grow their careers.
Top comments (0)