-
Notifications
You must be signed in to change notification settings - Fork 41
/
Copy pathAnswer72.cpp
41 lines (36 loc) · 811 Bytes
/
Answer72.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
bool isPossible(vector<int> &stalls, int k, int mid, int n) {
int cowCount = 1;
int lastPos = stalls[0];
for(int i=0; i<n; i++ ){
if(stalls[i]-lastPos >= mid){
cowCount++;
if(cowCount==k)
{
return true;
}
lastPos = stalls[i];
}
}
return false;
}
int aggressiveCows(vector<int> &stalls, int k)
{
sort(stalls.begin(), stalls.end());
int s = 0;
int n = stalls.size();
int e=stalls[n-1];
int ans = -1;
int mid = s + (e-s)/2;
while(s<=e) {
if(isPossible(stalls, k, mid, n)) {
ans = mid;
s = mid + 1;
}
else
{
e = mid - 1;
}
mid = s + (e-s)/2;
}
return ans;
}