-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathAggressiveCows.cpp
77 lines (65 loc) · 1.6 KB
/
AggressiveCows.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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
//{ Driver Code Starts
// Initial 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> &stalls, int distance, int cows)
{
int cntCows = 1;
int last = stalls[0];
for(int i = 0; i < stalls.size(); i++)
{
if(stalls[i] - last >= distance)
{
cntCows++;
last = stalls[i];
}
if(cntCows >= cows)
return true;
}
return false;
}
int solve(int n, int k, vector<int> &stalls) {
sort(stalls.begin(), stalls.end());
int ans = -1;
int low = 1;
int high = stalls[stalls.size() - 1];
while(low <= high)
{
int mid = (low + high)/2;
if(canWePlace(stalls, mid, k))
{
ans = mid;
low = mid+1;
}
else high = mid-1;
}
return ans;
}
};
//{ Driver Code Starts.
int main() {
int t = 1;
cin >> t;
// freopen ("output_gfg.txt", "w", stdout);
while (t--) {
// Input
int n, k;
cin >> n >> k;
vector<int> stalls(n);
for (int i = 0; i < n; i++) {
cin >> stalls[i];
}
// char ch;
// cin >> ch;
Solution obj;
cout << obj.solve(n, k, stalls) << endl;
// cout << "~\n";
}
// fclose(stdout);
return 0;
}
// } Driver Code Ends