forked from itsjohnty/Hacktoberfest
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathAggressive Cows.cpp
59 lines (32 loc) · 1004 Bytes
/
Aggressive Cows.cpp
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
// User function Template for C++
class Solution {
bool canPlaceCows(vector<int>& stalls, int n, int k, int distance) {
int cowsPlaced = 1;
int lastPos = stalls[0];
for (int i = 1; i < n; i++) {
if (stalls[i] - lastPos >= distance) {
cowsPlaced++;
lastPos = stalls[i];
}
}
return cowsPlaced >= k;
}
public:
int solve(int n, int k, vector<int> &stalls) {
// Write your code here
sort(stalls.begin(), stalls.end());
int start = 1;
int end = stalls[n - 1] - stalls[0];
int maxMinDistance = -1;
while (start <= end) {
int mid = start + (end - start) / 2;
if (canPlaceCows(stalls, n, k, mid)) {
maxMinDistance = mid;
start = mid + 1;
} else {
end = mid - 1;
}
}
return maxMinDistance;
}
};