-
Notifications
You must be signed in to change notification settings - Fork 0
/
Aggressive Cows.cpp
90 lines (65 loc) · 1.47 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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
//{ 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 possible(int n, int k, vector<int> &a,int mid)
{
int i,st=0;
k--;
for(i=1;i<n;i++)
{
if(a[i]-a[st]<mid)
continue;
k--;
st=i;
if(k==0)
return 1;
}
return k==0;
}
int solve(int n, int k, vector<int> &a) {
// Write your code here
sort(a.begin(),a.end());
int l=0,h=a[n-1]-a[0];
int ans=0;
while(l<=h)
{
int mid=(l+h)/2;
if(possible(n,k,a,mid))
{
ans=mid;
l=mid+1;
}
else
h=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