-
Notifications
You must be signed in to change notification settings - Fork 14
/
AggressiveCows.java
39 lines (36 loc) · 1.26 KB
/
AggressiveCows.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
import java.util.*;
public class AggressiveCows {
public static boolean canWePlace(int[] stalls, int dist, int cows) {
int n = stalls.length; //size of array
int cntCows = 1; //no. of cows placed
int last = stalls[0]; //position of last placed cow.
for (int i = 1; i < n; i++) {
if (stalls[i] - last >= dist) {
cntCows++; //place next cow.
last = stalls[i]; //update the last location.
}
if (cntCows >= cows) return true;
}
return false;
}
public static int aggressiveCows(int[] stalls, int k) {
int n = stalls.length; //size of array
//sort the stalls[]:
Arrays.sort(stalls);
int low = 1, high = stalls[n - 1] - stalls[0];
//apply binary search:
while (low <= high) {
int mid = (low + high) / 2;
if (canWePlace(stalls, mid, k) == true) {
low = mid + 1;
} else high = mid - 1;
}
return high;
}
public static void main(String[] args) {
int[] stalls = {0, 3, 4, 7, 10, 9};
int k = 4;
int ans = aggressiveCows(stalls, k);
System.out.println("The maximum possible minimum distance is: " + ans);
}
}