forked from HarshwardhanPatil07/HactoberFest2024
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathAggressiveCows
49 lines (44 loc) · 1.29 KB
/
AggressiveCows
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
39
40
41
42
43
44
45
46
47
48
49
import java.util.Arrays;
import java.util.Scanner;
public class AggressiveCows {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
int k = scanner.nextInt();
int[] arr = new int[n];
for (int i = 0; i < n; i++) {
arr[i] = scanner.nextInt();
}
System.out.println(maxMinDistance(arr, n, k));
}
private static boolean canPlaceCows(int[] arr, int n, int k, int minDist) {
int count = 1;
int lastPosition = arr[0];
for (int i = 1; i < n; i++) {
if (arr[i] - lastPosition >= minDist) {
count++;
lastPosition = arr[i];
if (count == k) {
return true;
}
}
}
return false;
}
private static int maxMinDistance(int[] arr, int n, int k) {
Arrays.sort(arr);
int low = 1;
int high = arr[n - 1] - arr[0];
int result = 0;
while (low <= high) {
int mid = (low + high) / 2;
if (canPlaceCows(arr, n, k, mid)) {
result = mid;
low = mid + 1;
} else {
high = mid - 1;
}
}
return result;
}
}