-
Notifications
You must be signed in to change notification settings - Fork 0
/
Minimize_the_heights_II.cpp
64 lines (48 loc) · 1.29 KB
/
Minimize_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
58
59
60
61
62
63
64
//{ 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) {
int n = arr.size();
if(n == 1) return 0;
sort(arr.begin(), arr.end());
int ans = arr[n-1] - arr[0];
int lowest = arr[0] + k;
int largest = arr[n-1] - k;
for(int i = 0; i < n-1; i++)
{
int mini = min(lowest, arr[i+1] - k);
int maxi = max(largest, arr[i] + k);
if(mini < 0) continue;
ans = min(ans, maxi-mini);
}
return ans;
}
};
//{ 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";
}
return 0;
}
// } Driver Code Ends