Skip to content
Related Articles
Open in App
Not now

Related Articles

Minimize the maximum difference between the heights

Improve Article
Save Article
Like Article
  • Difficulty Level : Hard
  • Last Updated : 22 Mar, 2023
Improve Article
Save Article
Like Article

Given the heights of N towers and a value of K, Either increase or decrease the height of every tower by K (only once) where K > 0. After modifications, the task is to minimize the difference between the heights of the longest and the shortest tower and output its difference.

Examples: 

Input: arr[] = {1, 15, 10}, k = 6
Output:  Maximum difference is 5.
Explanation: 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}

Recommended Practice

The idea for this is given below:

  • The idea is to increase the first i towers by k and decrease the rest tower by k after sorting the heights, then calculate the maximum height difference.
  • This can be achieved using sorting.

Illustration:

Given arr[] = {1, 15, 10}, n = 3, k = 6

Array after sorting => arr[] = {1, 10, 15}

Initially maxHeight = arr[n – 1] = 15
            minHeight = arr[0] = 1
            ans = maxHeight – minHeight = 15 – 1 = 14

At i = 1

  • minHeight = min(arr[0] + k, arr[i] – k) = min(1 + 6, 10 – 6) = 4
  • maxHeight = max(arr[i – 1] + k, arr[n – 1] – k) = max(1 + 6, 15 – 6) = 9
  • ans = min(ans, maxHeight – minHeight) = min(14, 9 – 4) = 5 => ans = 5

At i = 2

  • minHeight = min(arr[0] + k, arr[i] – k) = min(1 + 6, 15 – 6) = 7
  • maxHeight = max(arr[i – 1] + k, arr[n – 1] – k) = max(10 + 6, 15 – 6) = 16
  • ans = min(ans, maxHeight – minHeight) = min(5, 16 – 7) = 5 => ans = 5

Hence minimum difference is 5 

Note:- Consider where a[i] < K because the height of the tower can’t be negative so neglect that case. You may wonder that if we neglect this case, then we would also be neglecting a[i-1] + k; what if it is greater than a[n-1]-k? The answer for that is because a[i] < K, we don’t have any other option than to increase its height by K. And because a[i] > a[i-1], hence a[i] + k would also be greater than a[i-1]+k. Therefore, a[i-1] + k would never be the maximum height of the array and hence can be neglected.

Furthermore, the reason we don’t take a[i] for both minHeight and maxHeight is because it is possible that a[i] – k < arr[0] +k and at the same time a[i] +k > a[n-1] – k. In this scenario, we would be both increasing and decreasing the height of the tower which is not possible.

Follow the steps below to solve the given problem:

  • Sort the array 
  • Try to make each height of the tower maximum by decreasing the height of all the towers to the right by k and increasing all the height of the towers to the left by k. Check whether the current index tower has the maximum height or not by comparing it with a[n]-k. If the tower’s height is greater than the a[n]-k then it’s the tallest tower available.
  • Similarly, find the shortest tower and minimize the difference between these two towers.  

Below is the implementation of the above approach:

C++




// C++ Code for the Approach
 
#include <bits/stdc++.h>
using namespace std;
 
// User function Template
int getMinDiff(int arr[], int n, int k)
{
    sort(arr, arr + n);
 
    // 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 = min(arr[0] + k, arr[i] - k);
 
        // Maximum element when we
        // subtract k from whole array
        tempmax = max(arr[i - 1] + k, arr[n - 1] - k);
 
        ans = min(ans, tempmax - tempmin);
    }
    return ans;
}
 
// Driver Code Starts
int main()
{
 
    int k = 6, n = 6;
    int arr[n] = { 7, 4, 8, 8, 8, 9 };
 
    // Function Call
    int ans = getMinDiff(arr, n, k);
    cout << ans;
}


Java




/*package whatever //do not write package name here */
 
import java.io.*;
import java.util.*;
 
// Driver code
public 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;
    }
}


Python3




# User function Template
def 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):
        if arr[i] < k:
            continue
        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 Starts
k = 6
n = 6
arr = [7, 4, 8, 8, 8, 9]
ans = getMinDiff(arr, n, k)
print(ans)
 
# This code is contributed by ninja_hattori.


C#




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.


Javascript




<script>
 
// User function Template
function 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 Starts
let 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>


Output

5

Time Complexity: O(N * log(N)), Time is taken for sorting
Auxiliary Space: O(1)

Using Greedy Algorithm:

The idea behind this approach is to increase or decrease the heights of the towers in a way that moves the towers closer to the average height. By doing this, we can minimize the difference between the maximum and minimum heights.

Follow the steps below to solve the given problem:

  • Initialize the minimum and maximum heights in the array to arr[0].
  • Loop through the array and update the minimum and maximum heights as necessary. At the end of this step, we should have the minimum and maximum heights in the array.
  • Calculate the initial difference between the maximum and minimum heights.
  • Calculate the average height by taking the sum of the minimum and maximum heights and dividing it by 2.
  • Loop through the array and modify the heights of the towers as follows:
    a. If the height of a tower is less than or equal to the average height, increase its height by K.
    b. If the height of a tower is greater than the average height, decrease its height by K.
  • Calculate the new minimum and maximum heights in the modified array.
  • Calculate the new difference between the maximum and minimum heights.
  • If the new difference is greater than or equal to the initial difference, return the initial difference. Otherwise, return the new difference

Below is the implementation of above approach:

C++




// C++ Code for the Approach
#include <algorithm>
#include <cmath>
#include <iostream>
using namespace std;
 
int minimizeTowerHeightDifference(int arr[], int n, int k)
{
    // Find the minimum and maximum heights in the array
    int minHeight = *min_element(arr, arr + n);
    int maxHeight = *max_element(arr, arr + n);
 
    // Calculate the initial difference between the maximum
    // and minimum heights
    int initialDiff = maxHeight - minHeight;
 
    // Calculate the average height
    int avgHeight = (minHeight + maxHeight) / 2;
 
    // Modify the heights to minimize the difference between
    // the maximum and minimum heights
    for (int i = 0; i < n; i++) {
        if (arr[i] <= avgHeight) {
            arr[i] += k;
        }
        else {
            arr[i] -= k;
        }
    }
 
    // Find the new minimum and maximum heights in the array
    int newMinHeight = *min_element(arr, arr + n);
    int newMaxHeight = *max_element(arr, arr + n);
 
    // Calculate the new difference between the maximum and
    // minimum heights
    int newDiff = newMaxHeight - newMinHeight;
 
    // If the new difference is greater than the initial
    // difference, return the initial difference. Otherwise,
    // return the new difference.
    return (newDiff > initialDiff) ? initialDiff : newDiff;
}
//Driver code
int main()
{
    int arr[] = { 7, 4, 8, 8, 8, 9 };
    int n = sizeof(arr) / sizeof(arr[0]);
    int k = 6;
 
    int result = minimizeTowerHeightDifference(arr, n, k);
 
    cout << result << endl;
 
    return 0;
}
//This code is contributed by Veerendra_Singh_Rajpoot


Java




// Java Code for the Approach
import java.util.*;
 
public class Main {
    public static int
    minimizeTowerHeightDifference(int[] arr, int n, int k)
    {
        // Find the minimum and maximum heights in the array
        int minHeight = Arrays.stream(arr).min().getAsInt();
        int maxHeight = Arrays.stream(arr).max().getAsInt();
 
        // Calculate the initial difference between the
        // maximum and minimum heights
        int initialDiff = maxHeight - minHeight;
 
        // Calculate the average height
        int avgHeight = (minHeight + maxHeight) / 2;
 
        // Modify the heights to minimize the difference
        // between the maximum and minimum heights
        for (int i = 0; i < n; i++) {
            if (arr[i] <= avgHeight) {
                arr[i] += k;
            }
            else {
                arr[i] -= k;
            }
        }
 
        // Find the new minimum and maximum heights in the
        // array
        int newMinHeight
            = Arrays.stream(arr).min().getAsInt();
        int newMaxHeight
            = Arrays.stream(arr).max().getAsInt();
 
        // Calculate the new difference between the maximum
        // and minimum heights
        int newDiff = newMaxHeight - newMinHeight;
 
        // If the new difference is greater than the initial
        // difference, return the initial difference.
        // Otherwise, return the new difference.
        return (newDiff > initialDiff) ? initialDiff
                                       : newDiff;
    }
 
    // Driver code
    public static void main(String[] args)
    {
        int[] arr = { 7, 4, 8, 8, 8, 9 };
        int n = arr.length;
        int k = 6;
 
        int result
            = minimizeTowerHeightDifference(arr, n, k);
 
        System.out.println(result);
    }
}


Python3




def minimizeTowerHeightDifference(arr, n, k):
    # Find the minimum and maximum heights in the array
    minHeight = min(arr)
    maxHeight = max(arr)
 
    # Calculate the initial difference between the maximum
    # and minimum heights
    initialDiff = maxHeight - minHeight
 
    # Calculate the average height
    avgHeight = (minHeight + maxHeight) // 2
 
    # Modify the heights to minimize the difference between
    # the maximum and minimum heights
    for i in range(n):
        if arr[i] <= avgHeight:
            arr[i] += k
        else:
            arr[i] -= k
 
        # Find the new minimum and maximum heights in the array
    newMinHeight = min(arr)
    newMaxHeight = max(arr)
    # Calculate the new difference between the maximum and
    # minimum heights
    newDiff = newMaxHeight - newMinHeight
 
    # If the new difference is greater than the initial
    # difference, return the initial difference. Otherwise,
    # return the new difference.
    return initialDiff if newDiff > initialDiff else newDiff
 
# Driver code
arr = [7, 4, 8, 8, 8, 9]
n = len(arr)
k = 6
result = minimizeTowerHeightDifference(arr, n, k)
print(result)


C#




// C# program for the above approach
 
using System;
using System.Linq;
 
class MainClass {
  public static int minimizeTowerHeightDifference(int[] arr, int n, int k) {
    // Find the minimum and maximum heights in the array
    int minHeight = arr.Min();
    int maxHeight = arr.Max();
 
    // Calculate the initial difference between the
    // maximum and minimum heights
    int initialDiff = maxHeight - minHeight;
 
    // Calculate the average height
    int avgHeight = (minHeight + maxHeight) / 2;
 
    // Modify the heights to minimize the difference
    // between the maximum and minimum heights
    for (int i = 0; i < n; i++) {
      if (arr[i] <= avgHeight) {
        arr[i] += k;
      }
      else {
        arr[i] -= k;
      }
    }
 
    // Find the new minimum and maximum heights in the
    // array
    int newMinHeight = arr.Min();
    int newMaxHeight = arr.Max();
 
    // Calculate the new difference between the maximum
    // and minimum heights
    int newDiff = newMaxHeight - newMinHeight;
 
    // If the new difference is greater than the initial
    // difference, return the initial difference.
    // Otherwise, return the new difference.
    return (newDiff > initialDiff) ? initialDiff : newDiff;
  }
 
  public static void Main() {
    int[] arr = { 7, 4, 8, 8, 8, 9 };
    int n = arr.Length;
    int k = 6;
 
    int result = minimizeTowerHeightDifference(arr, n, k);
 
    Console.WriteLine(result);
  }
}
 
// This code is contributed by sdeadityasharma


Javascript




function minimizeTowerHeightDifference(arr, n, k) {
    // Find the minimum and maximum heights in the array
    let minHeight = Math.min(...arr);
    let maxHeight = Math.max(...arr);
 
    // Calculate the initial difference between the maximum
    // and minimum heights
    let initialDiff = maxHeight - minHeight;
 
    // Calculate the average height
    let avgHeight = Math.floor((minHeight + maxHeight) / 2);
 
    // Modify the heights to minimize the difference between
    // the maximum and minimum heights
    for (let i = 0; i < n; i++) {
        if (arr[i] <= avgHeight) {
            arr[i] += k;
        }
        else {
            arr[i] -= k;
        }
    }
 
    // Find the new minimum and maximum heights in the array
    let newMinHeight = Math.min(...arr);
    let newMaxHeight = Math.max(...arr);
 
    // Calculate the new difference between the maximum and
    // minimum heights
    let newDiff = newMaxHeight - newMinHeight;
 
    // If the new difference is greater than the initial
    // difference, return the initial difference. Otherwise,
    // return the new difference.
    return (newDiff > initialDiff) ? initialDiff : newDiff;
}
 
//Driver code
let arr = [7, 4, 8, 8, 8, 9];
let n = arr.length;
let k = 6;
 
let result = minimizeTowerHeightDifference(arr, n, k);
 
console.log(result);


Output

5

Time Complexity: O(N), where N refers to the number of towers.

Auxiliary Space: O(1), this is because we are not using any additional data structure.


My Personal Notes arrow_drop_up
Like Article
Save Article
Related Articles

Start Your Coding Journey Now!