-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSolution01.cpp
80 lines (63 loc) · 1.54 KB
/
Solution01.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
// GeeksforGeeks: https://www.geeksforgeeks.org/problems/aggressive-cows/0
//{ 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:
int solve(int n, int k, vector<int> &stalls) {
// Code
int start = 1, end, mid, ans;
// Sorting in increasing order
sort(stalls.begin(),stalls.end());
end = stalls[n-1]-stalls[0];
while(start<=end)
{
mid = start + (end - start)/2;
int count=1, position=stalls[0];
for(int i=1; i<n; i++)
{
if(position+mid<=stalls[i])
{
count++;
position=stalls[i];
}
}
if(count<k)
{
end=mid-1;
}
else
{
ans=mid;
start=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