-
Notifications
You must be signed in to change notification settings - Fork 0
/
GFG Aggressive Cows
79 lines (73 loc) · 1.56 KB
/
GFG Aggressive Cows
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
class Solution {
public:
int solve(int n, int k, vector<int> &stalls) {
sort(stalls.begin(),stalls.end());
int l=0;
int h=stalls[n-1];
int ans=-1;
while(l<=h)
{
int mid=l+(h-l)/2;
if(isPossible(mid,stalls,k))
{
ans=mid;
l=mid+1;
}
else
{
h=mid-1;
}
}
return ans;
}
bool isPossible(int mid,vector<int> &stalls,int k)
{
int last=0;
int count=1;
int n=stalls.size();
while(last<n)
{
auto lower=lower_bound(stalls.begin()+last,stalls.end(),stalls[last]+mid);
if(lower!=stalls.end())
{
int pos=lower-stalls.begin();
last=pos;
if(last>=n)
break;
++count;
}
else
break;
}
/*int n=stalls.size();
int l=0;
int h=n-1;
while(last<n)
{
l=last+1;
h=n-1;
int t=-1;
while(l<=h){
int m=l+(h-l)/2;
if(stalls[m]-stalls[last]>=mid)
{
t=m;
h=m-1;
}
else
{
l=m+1;
}
}
if(t!=-1)
last=t;
else
break;
++count;
}*/
if(count>=k)
return true;
else
return false;
}
};