Minimize the maximum difference between the heights

05 Jul, 2022
Given heights of n towers and a value k. We need to either increase or decrease the height of every tower by k (only once) where k > 0. The task is to minimize the difference between the heights of the longest and the shortest tower after modifications and output this difference.
Examples: 
Input  : arr[] = {1, 15, 10}, k = 6Output :  Maximum difference is 5.Explanation : We change 1 to 7, 15 to 9 and 10 to 4. Maximum difference is 5 (between 4 and 9). We can’t get a lower difference.
Input : arr[] = {1, 5, 15, 10}           k = 3   Output : Maximum difference is 8 arr[] = {4, 8, 12, 7}
Input : arr[] = {4, 6}          k = 10Output : Maximum difference is 2 arr[] = {14, 16} OR {-6, -4}
Input : arr[] = {6, 10}         k = 3Output : Maximum difference is 2 arr[] = {9, 7} 
Input : arr[] = {1, 10, 14, 14, 14, 15}        k = 6 Output: Maximum difference is 5 arr[] = {7, 4, 8, 8, 8, 9} 
Input : arr[] = {1, 2, 3}        k = 2 Output: Maximum difference is 2 arr[] = {3, 4, 5} 
Source: Adobe Interview Experience | Set 24 (On-Campus for MTS)
First, we try to sort the array and make each height of the tower maximum. We do this by decreasing the height of all the towers towards the right by k and increasing all the height of the towers towards the left (by k). It is also possible that the tower you are trying to increase the height doesn’t have the maximum height. Therefore we only need to check whether it has the maximum height or not by comparing it with the last element on the right side which is a[n]-k. Since the array is sorted if the tower’s height is greater than the [n]-k then it’s the tallest tower available. Similar reasoning can also be applied to finding the shortest tower.  
Note:- We need not consider where a[i]<k because the height of the tower can’t be negative so we have to neglect that case.
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
#include <bits/stdc++.h>using namespace std;  // User function Templateint getMinDiff(int arr[], int n, int k){    sort(arr, arr + n);    int ans = arr[n - 1] - arr[0]; // Maximum possible height difference      int tempmin, tempmax;    tempmin = arr[0];    tempmax = arr[n - 1];      for (int i = 1; i < n; i++) {        if(arr[i] - k < 0) // if on subtracting k we got negative then continue         continue;        tempmin= min(arr[0] + k,arr[i] - k); // Minimum element when we                                                // add k to whole array        tempmax = max(arr[i - 1] + k, arr[n - 1] - k); // Maximum element when we                                                         // subtract k from whole array        ans = min(ans, tempmax - tempmin);     }    return ans;}  // Driver Code Startsint main(){    int k = 6, n = 6;    int arr[n] = { 7, 4, 8, 8, 8, 9 };    int ans = getMinDiff(arr, n, k);    cout << ans;}
/*package whatever //do not write package name here */  import java.io.*;import java.util.*;  // Driver codepublic class Main {      public static void main(String[] args)    {        int[] arr = { 7, 4, 8, 8, 8, 9 };        int k = 6;        int ans = getMinDiff(arr, arr.length, k);        System.out.println(ans);    }      // User function Template for Java    public static int getMinDiff(int[] arr, int n, int k)    {          Arrays.sort(arr);        // Maximum possible height difference        int ans = arr[n - 1] - arr[0];          int tempmin, tempmax;        tempmin = arr[0];        tempmax = arr[n - 1];          for (int i = 1; i < n; i++) {              // if on subtracting k we got negative then            // continue            if (arr[i] - k < 0)                continue;              // Minimum element when we add k to whole array            tempmin = Math.min(arr[0] + k, arr[i] - k);              // Maximum element when we subtract k from whole            // array            tempmax                = Math.max(arr[i - 1] + k, arr[n - 1] - k);            ans = Math.min(ans, tempmax - tempmin);        }        return ans;    }}
# User function Templatedef getMinDiff(arr, n, k):    arr.sort()    ans = arr[n - 1] - arr[0]  # Maximum possible height difference      tempmin = arr[0]    tempmax = arr[n - 1]      for i in range(1, n):        tempmin = min(arr[0] + k, arr[i] - k)                    # Minimum element when we        # add k to whole array        # Maximum element when we        tempmax = max(arr[i - 1] + k, arr[n - 1] - k)                  # subtract k from whole array        ans = min(ans, tempmax - tempmin)      return ans  # Driver Code Startsk = 6n = 6arr = [7, 4, 8, 8, 8, 9]ans = getMinDiff(arr, n, k)print(ans)  # This code is contributed by ninja_hattori.
using System;  public class GFG {    static public int getMinDiff(int[] arr, int n, int k)  {      Array.Sort(arr);    int ans      = (arr[n - 1] + k)      - (arr[0]         + k); // Maximum possible height difference      int tempmax      = arr[n - 1] - k; // Maximum element when we    // subtract k from whole array    int tempmin = arr[0] + k; // Minimum element when we    // add k to whole array    int max, min;      for (int i = 0; i < n - 1; i++) {      if (tempmax > (arr[i] + k)) {        max = tempmax;      }      else {        max = arr[i] + k;      }        if (tempmin < (arr[i + 1] - k)) {        min = tempmin;      }      else {        min = arr[i + 1] - k;      }        if (ans > (max - min)) {        ans = max - min;      }    }    return ans;  }    static public void Main()  {    int[] arr = { 7, 4, 8, 8, 8, 9 };    int k = 6;    int ans = getMinDiff(arr, arr.Length, k);    Console.Write(ans);  }}  // This code is contributed by ninja_hattori.
<script>  // User function Templatefunction getMinDiff(arr,n,k){    arr.sort((a,b) => (a-b))    let ans = arr[n - 1] - arr[0]; // Maximum possible height difference      let tempmin, tempmax;    tempmin = arr[0];    tempmax = arr[n - 1];      for (let i = 1; i < n; i++) {        tempmin= Math.min(arr[0] + k,arr[i] - k); // Minimum element when we                                                // add k to whole array        tempmax = Math.max(arr[i - 1] + k, arr[n - 1] - k); // Maximum element when we                                                         // subtract k from whole array        ans = Math.min(ans, tempmax - tempmin);     }    return ans;}  // Driver Code Startslet k = 6, n = 6;let arr = [ 7, 4, 8, 8, 8, 9 ];let ans = getMinDiff(arr, n, k);document.write(ans,"</br>");  //This code is contributed by shinjanpatra.</script>
5
Time Complexity: O(nlogn)Auxiliary Space: O(n)
ukasp
ihritik
SHIKHAR AGRAWAL
avanitrachhadiya2155
gautampraveen351
sudhanshublaze
suyashsincever13
adityapawar666
lucky_002
swapnilakash21
kalrap615
u19cs070
shivanshchaudhary18
himanshu000choudhary
mrigankvashist
ninja_hattori
shinjanpatra
eni_g
ayushrajput1410
naitikvarshneyintern
hardikkoriintern
Adobe
Arrays
Greedy
Adobe
Arrays
Greedy
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.