-
Notifications
You must be signed in to change notification settings - Fork 0
/
Aggressive_cow.cpp
90 lines (70 loc) · 1.51 KB
/
Aggressive_cow.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 {
private:
bool ifpossible(vector<int> &stalls, int k,int mid){
int cc=1;
int ls=stalls[0];
for(int i=0; i<stalls.size();i++){
if(stalls[i]-ls>= mid){
cc++;
if(cc==k){
return true;
}
ls=stalls[i];
}
}
return false;
}
public:
int solve(int n, int k, vector<int> &stalls) {
// Write your code here
sort(stalls.begin(),stalls.end());
int s=0;
int maxi=-1;
for(int i=0; i<stalls.size();i++ ){
maxi=max(maxi,stalls[i]);
}
int e=maxi;
int ans= -1;
int mid= s+(e-s)/2;
while(s<=e){
if(ifpossible(stalls,k ,mid)){
ans=mid;
s=mid+1;
}
else{
e=mid-1;
}
mid=s+(e-s)/2;
}
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