-
Notifications
You must be signed in to change notification settings - Fork 0
/
Aggressive cows
49 lines (43 loc) · 901 Bytes
/
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
bool ispossible(vector<int> &stalls, int k , int dif)
{
vector <int> arr= stalls ;
int n = stalls.size() ;
int i = 0 ;
int j = 1;
int c = 1 ;
while(i <n && j < n)
{
if(arr[j] - arr[i] >= dif)
{
c++;
i = j ;
j = i + 1 ;
}
else
{
j++ ;
}
}
return c >= k ;
}
int aggressiveCows(vector<int> &stalls, int k) {
// Write your code here.
int l = 1 ;
int res = -1e9 ;
sort(stalls.begin(),stalls.end()) ;
int r = *max_element(stalls.begin(),stalls.end()) - *min_element(stalls.begin(),stalls.end()) ;
while( l <= r)
{
int mid = (l + r) / 2 ;
bool a = ispossible(stalls , k ,mid) ;
// cout << mid << " " << a << endl ;
if (a) {
res = max(mid, res);
l = mid + 1 ;
}
else{
r = mid - 1 ;
}
}
return res ;
}