-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAggressive Cows
More file actions
79 lines (71 loc) · 2.69 KB
/
Aggressive Cows
File metadata and controls
79 lines (71 loc) · 2.69 KB
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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
Aggressive Cows
Difficulty: MediumAccuracy: 59.57%Submissions: 96K+Points: 4
You are given an array with unique elements of stalls[], which denote the position of a stall. You are also given an integer k which denotes the number of aggressive cows. Your task is to assign stalls to k cows such that the minimum distance between any two of them is the maximum possible.
Examples :
Input: stalls[] = [1, 2, 4, 8, 9], k = 3
Output: 3
Explanation: The first cow can be placed at stalls[0],
the second cow can be placed at stalls[2] and
the third cow can be placed at stalls[3].
The minimum distance between cows, in this case, is 3, which also is the largest among all possible ways.
Input: stalls[] = [10, 1, 2, 7, 5], k = 3
Output: 4
Explanation: The first cow can be placed at stalls[0],
the second cow can be placed at stalls[1] and
the third cow can be placed at stalls[4].
The minimum distance between cows, in this case, is 4, which also is the largest among all possible ways.
Input: stalls[] = [2, 12, 11, 3, 26, 7], k = 5
Output: 1
Explanation: Each cow can be placed in any of the stalls, as the no. of stalls are exactly equal to the number of cows.
The minimum distance between cows, in this case, is 1, which also is the largest among all possible ways.
Constraints:
2 <= stalls.size() <= 106
0 <= stalls[i] <= 108
1 <= k <= stalls.size()
class Solution {
static int ceilSearch(int[] arr, int low, int high, int x) {
int mid;
if (x <= arr[low]) return low;
if (x > arr[high]) return -1;
mid = (low + high) / 2;
if (arr[mid] == x)
return mid;
else if (arr[mid] < x) {
if (mid + 1 <= high && x <= arr[mid + 1])
return mid + 1;
else
return ceilSearch(arr, mid + 1, high, x);
} else {
if (mid - 1 >= low && x > arr[mid - 1])
return mid;
else
return ceilSearch(arr, low, mid - 1, x);
}
}
static boolean valid(int[] a, int c, int x) {
int n = a.length;
int pos = a[0];
int cow = 1;
while (pos <= a[n - 1]) {
pos += x;
int ind = ceilSearch(a, 0, n - 1, pos);
if (ind == -1) return false;
pos = a[ind];
cow++;
if (cow >= c) return true;
}
return cow >= c;
}
public int aggressiveCows(int[] a, int k) {
int n = a.length;
Arrays.sort(a);
int low = 0, high = (int)1e9;
while (low + 1 < high) {
int mid = low + (high - low) / 2;
if (valid(a, k, mid))
low = mid;
else
high = mid;
}
return low;
}}