-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMinimise the Heights II.cpp
57 lines (50 loc) · 1.15 KB
/
Minimise the Heights II.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
//{ 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 getMinDiff(vector<int> &arr, int k) {
// code here
int n=arr.size();
sort(arr.begin(),arr.end());
int res = arr[n-1] - arr[0];
for(int i=0;i<n;i++)
{
if((arr[i]-k) < 0)
{
continue;
}
int mini = min(arr[0] + k ,arr[i] - k);
int maxi = max(arr[i-1]+k , arr[n-1]-k);
res = min(res,maxi-mini);
}
return res;
}
};
//{ Driver Code Starts.
int main() {
int t;
cin >> t;
cin.ignore();
while (t--) {
int n, k;
cin >> k;
cin.ignore();
vector<int> a, b, c, d;
string input;
getline(cin, input);
stringstream ss(input);
int num;
while (ss >> num)
a.push_back(num);
Solution ob;
auto ans = ob.getMinDiff(a, k);
cout << ans << "\n";
cout << '~' << endl;
}
return 0;
}
// } Driver Code Ends