|
| 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 | + //sort the array first |
| 23 | + sort(arr, arr+n); |
| 24 | + |
| 25 | + //store the difference between first and last value. |
| 26 | + int ans = arr[n-1] - arr[0]; |
| 27 | + |
| 28 | + for(int i = 0; i < n-1; i++) { |
| 29 | + if(arr[i+1] < k) { |
| 30 | + continue; |
| 31 | + } |
| 32 | + //currMin will have minimum value after update |
| 33 | + int currMin = min(arr[i+1]-k, arr[0]+k); |
| 34 | + //currMax will have maximum value after update |
| 35 | + int currMax = max(arr[i]+k, arr[n-1]-k); |
| 36 | + //minimum value between previous answers and current difference will be saved in ans variable. |
| 37 | + ans = min(ans, currMax-currMin); |
| 38 | + } |
| 39 | + |
| 40 | + return ans; |
| 41 | + } |
| 42 | +}; |
| 43 | + |
| 44 | +int main(){ |
| 45 | + int n,k; |
| 46 | + |
| 47 | + //Accept length of the array |
| 48 | + cin>>n; |
| 49 | + //K is the number by which the values will be increased/decreased |
| 50 | + cin>>k; |
| 51 | + |
| 52 | + int arr[n]; |
| 53 | + //loop to accept array values |
| 54 | + for(int i=0;i<n;i++){ |
| 55 | + cin>>arr[i]; |
| 56 | + } |
| 57 | + //creating object of Solution class and saving the returned value in min_diff variable. |
| 58 | + Solution obj; |
| 59 | + int min_diff = obj.getMinDiff(arr,n,k); |
| 60 | + |
| 61 | + //print the final answer |
| 62 | + cout<<"The difference between the largest and smallest is: " << min_diff<< "\n"; |
| 63 | + |
| 64 | + return 0; |
| 65 | +} |
0 commit comments