Skip to content

Commit 26af3fc

Browse files
Add files via upload
1 parent c1eacc3 commit 26af3fc

File tree

1 file changed

+54
-0
lines changed

1 file changed

+54
-0
lines changed

Arrays/Minimize_the_height.cpp

Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
/*
2+
Find the possible minimum difference of the height of shortest and longest towers after you have modified each tower.
3+
4+
Input:
5+
K = 3, N = 5
6+
Arr[] = {3, 9, 12, 16, 20}
7+
Output:
8+
11
9+
Explanation:
10+
The array can be modified as
11+
{6, 12, 9, 13, 17}. The difference between
12+
the largest and the smallest is 17-6 = 11.
13+
*/
14+
15+
#include<iostream>
16+
#include<algorithm>
17+
using namespace std;
18+
19+
class Solution {
20+
public:
21+
int getMinDiff(int arr[], int n, int k) {
22+
// code here
23+
sort(arr, arr+n);
24+
25+
int ans = arr[n-1] - arr[0];
26+
27+
for(int i = 0; i < n-1; i++) {
28+
if(arr[i+1] < k) {
29+
continue;
30+
}
31+
int currMin = min(arr[i+1]-k, arr[0]+k);
32+
int currMax = max(arr[i]+k, arr[n-1]-k);
33+
ans = min(ans, currMax-currMin);
34+
}
35+
36+
return ans;
37+
}
38+
};
39+
40+
int main(){
41+
int n,k;
42+
cin>>n;
43+
cin>>k;
44+
int arr[n];
45+
46+
for(int i=0;i<n;i++){
47+
cin>>arr[i];
48+
}
49+
Solution obj;
50+
int min_diff = obj.getMinDiff(arr,n,k);
51+
cout<<"The difference between the largest and smallest is: " << min_diff<< "\n";
52+
53+
return 0;
54+
}

0 commit comments

Comments
 (0)