-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path24. Aggressive Cows
86 lines (77 loc) · 1.81 KB
/
24. 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
80
81
82
83
84
85
86
//{ Driver Code Starts
// Initial function template for C++
#include <bits/stdc++.h>
using namespace std;
// } Driver Code Ends
// User function Template for C++
class Solution {
public:
bool Canweplace(vector<int> &a, int d, int cows, int size)
{
int count = 1, prev = a[0]; //one cow is already placed so count = 1
for(int i = 1; i < size; i++)
{
if(a[i] - prev >= d)
{
count++;
prev = a[i];
}
if(count >= cows)
{
return true;
}
}
return false;
}
int aggressiveCows(vector<int> &stalls, int k) {
// Write your code here
sort(stalls.begin(), stalls.end());
int n = stalls.size();
int ans = 0;
int lo = 1, hi = stalls[n - 1] - stalls[0];
while(lo <= hi)
{
int mid = (lo + hi) / 2;
if(Canweplace(stalls, mid, k, n) == true)
{
ans = mid;
lo = mid + 1;
}
else
{
hi = mid - 1;
}
}
return ans;
}
};
//{ Driver Code Starts.
int main() {
int test_case;
cin >> test_case;
cin.ignore();
while (test_case--) {
int k;
vector<int> arr;
string input;
getline(cin, input);
stringstream ss(input);
int number;
while (ss >> number) {
arr.push_back(number);
}
string in;
getline(cin, in);
stringstream sss(in);
int num;
while (sss >> num) {
k = num;
}
Solution ob;
int ans = ob.aggressiveCows(arr, k);
cout << ans << endl;
cout << "~" << endl;
}
return 0;
}
// } Driver Code Ends