forked from krimanisha/Hacktoberfest21
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathaggressive_cows.cpp
More file actions
47 lines (42 loc) · 869 Bytes
/
aggressive_cows.cpp
File metadata and controls
47 lines (42 loc) · 869 Bytes
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
#include <bits/stdc++.h>
using namespace std;
bool canPlaceCows(int arr[], int n, int cows, int distance)
{
int coordinate = arr[0], count = 1;
for (int i = 1; i < n; i++)
{
if (arr[i] - coordinate >= distance)
{
count++;
coordinate = arr[i];
}
if (count == cows)
{
return true;
}
}
return false;
}
int main()
{
int arr[] = {1, 2, 8, 4, 9};
int n = sizeof(arr) / sizeof(arr[0]);
int cows = 3;
sort(arr, arr + n);
int low = 1, high = arr[n - 1] - arr[0], res;
while (low <= high)
{
int mid = (low + high) >> 1;
if (canPlaceCows(arr, n, cows, mid))
{
res = mid;
low = mid + 1;
}
else
{
high = mid - 1;
}
}
cout << res;
return 0;
}