-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAggressiveCows.java
More file actions
36 lines (30 loc) · 847 Bytes
/
AggressiveCows.java
File metadata and controls
36 lines (30 loc) · 847 Bytes
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
package Searching;
import java.util.Arrays;
public class AggressiveCows {
public static int solve(int n, int k, int[] stalls) {
Arrays.sort(stalls);
if (k > n) return -1;
int st = 0, end = (int) 1e9, ans = -1;
while (st <= end) {
int mid = st + (end - st) / 2;
if (isPossible(stalls, k, mid)) {
ans = mid;
st = mid + 1;
} else {
end = mid - 1;
}
}
return ans;
}
static boolean isPossible(int[] a, int k, int dist) {
int cowsPlaces = 1;
int lastCow = a[0];
for (int i = 1; i < a.length; i++) {
if (a[i] - lastCow >= dist) {
cowsPlaces++;
lastCow = a[i];
}
}
return cowsPlaces >= k;
}
}