forked from monuverma1501/HactoberFest2022
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Aggressive cows.cpp
62 lines (58 loc) · 1.21 KB
/
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
60
61
62
#include<bits/stdc++.h>
using namespace std;
bool isPossible(vector<int>& stalls , int n , int k , int mid)
{
int cowsCount = 1;
int cowsDistance = stalls[0];
for(int i= 0 ; i< n ;i++)
{
if(stalls[i] - cowsDistance >= mid)
{
cowsCount++;
if(cowsCount == k)
{
return true;
}
cowsDistance = stalls[i];
}
}
return false;
}
int aggresiveCows(vector<int> &stalls , int n , int k)
{
sort(stalls.begin() , stalls.end());
int start = 0;
int maxi = -1;
for(int i=0 ; i<n ; i++){
maxi = max(maxi , stalls[i]);
}
int end = maxi;
int mid = start + (end - start)/2;
int ans = -1;
while(start <= end)
{
if(isPossible(stalls , n , k , mid)){
ans = mid;
start = mid + 1;
}
else{
end = mid - 1;
}
mid = start + (end - start)/2;
}
return ans;
}
int main()
{
int n , k;
cin >> n >> k;
vector<int> arr;
for(int i=0 ;i<n ; i++){
int x;
cin >> x;
arr.push_back(x);
}
int ans = aggresiveCows(arr , n , k);
cout << ans;
return 0;
}