-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathminimizeTheHeights.cpp
More file actions
47 lines (44 loc) · 1.46 KB
/
minimizeTheHeights.cpp
File metadata and controls
47 lines (44 loc) · 1.46 KB
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
//Given an array arr[] denoting heights of N towers and a positive integer K, you have to modify the height of each tower either by increasing or decreasing them by K only once. After modifying, height should be a non-negative integer.
//Find out what could be the possible minimum difference of the height of shortest and longest towers after you have modified each tower
#include <bits/stdc++.h>
using namespace std;
class Solution{
public:
int getMinDiff(int arr[], int n, int k) {
int i,j,maxl=0,minl=0,max=arr[0],min=arr[0];
for(i=1;i<n;i++)
{
//finding max and min element of array before modifying
if(arr[i]>max){
max=arr[i];
maxl=i;
}
if(arr[i]<min){
min=arr[i];
minl=i;
}
}
for(i=0;i<n;i++)
{
//increasing /decreasing elements according to max and min values to avoid overcomes
if(arr[i]+k>max-k)
arr[i]=arr[i]-k;
else if(arr[i]-k<min+k)
arr[i]=arr[i]+k;
}
int difference=arr[maxl]-arr[minl];
return difference;
}
};
int main() {
int n, k;
cin >> k;
cin >> n;
int arr[n];
for (int i = 0; i < n; i++) {
cin >> arr[i];
Solution ob;
auto ans = ob.getMinDiff(arr, n, k);
cout << ans << "\n";
return 0;
}