The Wayback Machine - https://web.archive.org/web/20241005005445/https://www.geeksforgeeks.org/minimize-the-maximum-difference-between-the-heights/
Open In App

Minimize the maximum difference between the heights

Last Updated : 30 Sep, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow
Solve Problem
Medium
15.06%
6.1L

Given the heights of n towers and a positive integer k, increase or decrease the height of all towers by k (only once). After modifications, the task is to find the minimum difference between the heights of the tallest and the shortest tower.

Examples: 

Input: arr[] = {12, 6, 4, 15, 17, 10}, k = 6
Output: 8
Explanation: Update arr[] as {12 – 6, 6 + 6, 4 + 6, 15 – 6, 17 – 6, 10 – 6} = {6, 12, 10, 9, 11, 4}. Now, the minimum difference is 12 – 4 = 8.

Input: arr[] = {12, 6, 4, 15, 17, 10}, k = 3
Output: 8
Explanation: Update arr[] as {1 + 3, 5 + 3, 10 – 3, 15 – 3} = {4, 8, 7, 12}. Now, the minimum difference is 8.

Using Sorting – O(nlogn) Time and O(1) Space

The idea is to sort the array and check the maximum height difference at each index by increasing the height of towers up to that index and decreasing the height of towers beyond that index.

For any index i, if we add k to all heights in subarray arr[0…i-1] and subtract k from all heights in subarray arr[i…n-1], then we know that smallest height = min(arr[0]+k, arr[i]-k) and tallest height = min(arr[i-1]+k, arr[n-1]-k). So, the smallest difference between tallest height and smallest height over all indices will be the result.

We can see that for any index i, the smallest height depends on arr[0] and arr[i] and the tallest height depends on arr[i – 1] and arr[n – 1], so instead of modifying the subarrays arr[0…i-1] and arr[i…n-1], we can simply modify arr[0], arr[i – 1], arr[i] and arr[n – 1] to get the smallest difference between heights.

C++
// C++ program to minimize the maximum difference
// between heights using Sorting

#include <bits/stdc++.h>
using namespace std;

// Function to minimize the maximum difference
int getMinDiff(vector<int> &arr, int k) {
    int n = arr.size();
    sort(arr.begin(), arr.end());
  
    // If we increase all heights by k or decrease all
    // heights by k, the result will be arr[n - 1] - arr[0]
    int res = arr[n - 1] - arr[0];

    //  For all indices i, increment arr[0...i-1] by k and
    // decrement arr[i...n-1] by k
    for (int i = 1; i < arr.size(); i++) {
      
        // Impossible to decrement height of ith tower by k, 
        // continue to the next tower
        if (arr[i] - k < 0)
            continue;
      
        // Minimum height after modification
        int minH = min(arr[0] + k, arr[i] - k);
      
        // Maximum height after modification
        int maxH = max(arr[i - 1] + k, arr[n - 1] - k);

        // Store the minimum difference as result
        res = min(res, maxH - minH);
    }
    return res;
}

int main() {

    int k = 6;
    vector<int> arr = {12, 6, 4, 15, 17, 10};

    int ans = getMinDiff(arr, k);
    cout << ans;

    return 0;
}
C
// C program to minimize the maximum difference
// between heights using Sorting

#include <stdio.h>
#include <stdlib.h>

// Function to compare two integers (for qsort)
int compare(const void *a, const void *b) {
    return (*(int*)a - *(int*)b);
}

// Function to minimize the maximum difference
int getMinDiff(int arr[], int n, int k) {
    qsort(arr, n, sizeof(int), compare);

    // If we increase all heights by k or decrease all
    // heights by k, the result will be arr[n - 1] - arr[0]
    int res = arr[n - 1] - arr[0];

    // For all indices i, increment arr[0...i-1] by k and
    // decrement arr[i...n-1] by k
    for (int i = 1; i < n; i++) {
        // Impossible to decrement height of ith tower by k,
        // continue to the next tower
        if (arr[i] - k < 0)
            continue;

        // Minimum height after modification
        int minH = (arr[0] + k < arr[i] - k) ? (arr[0] + k) : (arr[i] - k);

        // Maximum height after modification
        int maxH = (arr[i - 1] + k > arr[n - 1] - k) ? (arr[i - 1] + k) : (arr[n - 1] - k);

        // Store the minimum difference as result
        res = (res < maxH - minH) ? res : (maxH - minH);
    }
    return res;
}

int main() {
    int k = 6;
    int arr[] = {12, 6, 4, 15, 17, 10};
    int n = sizeof(arr) / sizeof(arr[0]);

    int ans = getMinDiff(arr, n, k);
    printf("%d\n", ans);

    return 0;
}
Java
// Java program to minimize the maximum difference
// between heights using Sorting

import java.util.Arrays;

class GfG {

    // Function to minimize the maximum difference
    static int getMinDiff(int[] arr, int k) {
        int n = arr.length;
        Arrays.sort(arr);

        // If we increase all heights by k or decrease all
        // heights by k, the result will be arr[n - 1] - arr[0]
        int res = arr[n - 1] - arr[0];

        // For all indices i, increment arr[0...i-1] by k and
        // decrement arr[i...n-1] by k
        for (int i = 1; i < arr.length; i++) {

            // Impossible to decrement height of ith tower by k, 
            // continue to the next tower
            if (arr[i] - k < 0)
                continue;

            // Minimum height after modification
            int minH = Math.min(arr[0] + k, arr[i] - k);

            // Maximum height after modification
            int maxH = Math.max(arr[i - 1] + k, arr[n - 1] - k);

            // Store the minimum difference as result
            res = Math.min(res, maxH - minH);
        }
        return res;
    }

    public static void main(String[] args) {
        int k = 6;
        int[] arr = {12, 6, 4, 15, 17, 10};

        int ans = getMinDiff(arr, k);
        System.out.println(ans);
    }
}
Python
# Python program to minimize the maximum difference
# between heights using Sorting

def getMinDiff(arr, k):
    n = len(arr)
    arr.sort()

    # If we increase all heights by k or decrease all
    # heights by k, the result will be arr[n - 1] - arr[0]
    res = arr[n - 1] - arr[0]

    # For all indices i, increment arr[0...i-1] by k and
    # decrement arr[i...n-1] by k
    for i in range(1, len(arr)):
        # Impossible to decrement height of ith tower by k, 
        # continue to the next tower
        if arr[i] - k < 0:
            continue

        # Minimum height after modification
        minH = min(arr[0] + k, arr[i] - k)

        # Maximum height after modification
        maxH = max(arr[i - 1] + k, arr[n - 1] - k)

        # Store the minimum difference as result
        res = min(res, maxH - minH)
    
    return res

if __name__ == "__main__":
    k = 6
    arr = [12, 6, 4, 15, 17, 10]

    ans = getMinDiff(arr, k)
    print(ans)
C#
// C# program to minimize the maximum difference
// between heights using Sorting

using System;

class GfG {
    
    // Function to minimize the maximum difference
    public static int getMinDiff(int[] arr, int k) {
        int n = arr.Length;
        Array.Sort(arr);

        // If we increase all heights by k or decrease all
        // heights by k, the result will be arr[n - 1] - arr[0]
        int res = arr[n - 1] - arr[0];

        // For all indices i, increment arr[0...i-1] by k and
        // decrement arr[i...n-1] by k
        for (int i = 1; i < arr.Length; i++) {
            
            // Impossible to decrement height of ith tower by k, 
            // continue to the next tower
            if (arr[i] - k < 0)
                continue;

            // Minimum height after modification
            int minH = Math.Min(arr[0] + k, arr[i] - k);

            // Maximum height after modification
            int maxH = Math.Max(arr[i - 1] + k, arr[n - 1] - k);

            // Store the minimum difference as result
            res = Math.Min(res, maxH - minH);
        }
        return res;
    }

    static void Main() {
        int k = 6;
        int[] arr = { 12, 6, 4, 15, 17, 10 };

        int ans = getMinDiff(arr, k);
        Console.WriteLine(ans);
    }
}
JavaScript
// JavaScript program to minimize the maximum difference
// between heights using Sorting

function getMinDiff(arr, k) {
    const n = arr.length;
    arr.sort((a, b) => a - b);

    // If we increase all heights by k or decrease all
    // heights by k, the result will be arr[n - 1] - arr[0]
    let res = arr[n - 1] - arr[0];

    // For all indices i, increment arr[0...i-1] by k and
    // decrement arr[i...n-1] by k
    for (let i = 1; i < arr.length; i++) {
        
        // Impossible to decrement height of ith tower by k, 
        // continue to the next tower
        if (arr[i] - k < 0)
            continue;

        // Minimum height after modification
        let minH = Math.min(arr[0] + k, arr[i] - k);

        // Maximum height after modification
        let maxH = Math.max(arr[i - 1] + k, arr[n - 1] - k);

        // Store the minimum difference as result
        res = Math.min(res, maxH - minH);
    }
    return res;
}

const k = 6;
const arr = [12, 6, 4, 15, 17, 10];

const ans = getMinDiff(arr, k);
console.log(ans);

Output
8

Time Complexity: O(nlogn), as we are sorting the array.
Auxiliary Space: O(1)



Previous Article
Next Article

Similar Reads

Minimize cost of operation to equalize tower heights
Given heights of n (n <=10000) towers as an array h[]; we need to bring every tower to same height by either adding or removing blocks in a tower. Every addition or removal operation costs a different value in a different tower. The objective is to minimize this cost. Examples: Input : Tower heights h[] = {1, 2, 3} Costs of operations cost[] = {
11 min read
Sum of heights of all individual nodes in a binary tree
Given a binary tree, find the sum of heights of all individual nodes in the tree. Example: For this tree: 1). Height of Node 1 - 3 2). Height of Node 2 - 2 3). Height of Node 3 - 1 4). Height of Node 4 - 1 5). Height of Node 5 - 1 Adding all of them = 8 Prerequisites:- Height of binary tree Simple Solution: We get the height of all individual nodes
11 min read
Print the Matrix after increasing the heights of the blocks
Given a 0-based n x n integer matrix where grid[x][y] represents the height of the blocks in row x and column y. You can increase the height of any block (different per block), but the increased height of a block should not change the contour formed. Contour is the view of blocks from a distance in any direction, the task is to print the matrix aft
7 min read
Minimize Y for given N to minimize difference between LCM and GCD
Given an integer N, the task is to find a minimum possible Y that satisfies the following condition: Y > N.Y is not divisible by N (except N = 1).The absolute difference of gcd and lcm of N and Y i.e. | gcd(N, Y)?lcm(N, Y) | is as minimum as possible Examples: Input: N = 3 Output: 4?Explanation: When Y = 4 is taken then GCD(3, 4) = 1 and LCM(3,
5 min read
Minimize the difference between minimum and maximum elements
Given an array of [Tex]N [/Tex]integers and an integer [Tex]k [/Tex]. It is allowed to modify an element either by increasing or decreasing them by k (only once).The task is to minimize and print the maximum difference between the shortest and longest towers. Examples: Input: arr[] = {1, 10, 8, 5}, k = 2 Output : Max height difference = 5 Explanati
8 min read
Minimize the difference between the maximum and minimum values of the modified array
Given an array A of n integers and integer X. You may choose any integer between [Tex]-X\leq k\leq X [/Tex], and add k to A[i] for each [Tex]0\leq i \leq n-1 [/Tex]. The task is to find the smallest possible difference between the maximum value of A and the minimum value of A after updating array A. Examples: Input: arr[] = {1, 3, 6}, x = 3 Output:
5 min read
Minimize the maximum difference between adjacent elements in an array
Given a non-decreasing array arr[] and an integer K, the task is to remove K elements from the array such that maximum difference between adjacent element is minimum.Note: K < N - 2 Examples: Input: arr[] = {3, 7, 8, 10, 14}, K = 2 Output: 2 Explanation: After removing elements A[0] and A[4], The maximum difference between adjacent elements is m
15+ min read
Minimize count of Subsets with difference between maximum and minimum element not exceeding K
Given an array arr[ ] and an integer K, the task is to split the given array into minimum number of subsets having the difference between the maximum and the minimum element â‰Ī K. Examples: Input: arr[ ] = {1, 3, 7, 9, 10}, K = 3Output: 2Explanation:One of the possible subsets of arr[] are {1, 3} and {7, 9, 10} where the difference between maximum a
5 min read
Minimize maximum difference between any pair of array elements by exactly one removal
Given an array arr[] consisting of N integers(N > 2), the task is to minimize the maximum difference between any pair of elements (arr[i], arr[j]) by removing exactly one element. Examples: Input: arr[] = {1, 3, 4, 7}Output: 3Explanation:Removing the element 7 from array, modifies the array to {1, 3, 4}.Here (4, 1) has difference = 4 – 1 = 3 whi
9 min read
Minimize difference between maximum and minimum array elements by exactly K removals
Given an array arr[] consisting of N positive integers and an integer K, the task is to minimize the difference between the maximum and minimum element in the given array after removing exactly K elements. Examples: Input: arr[] = {5, 1, 6, 7, 12, 10}, K = 3Output: 2Explanation:Remove elements 12, 10 and 1 from the given array.The array modifies to
6 min read
Minimize difference between maximum and minimum array elements by removing a K-length subarray
Given an array arr[] consisting of N integers and an integer K, the task is to find the minimum difference between the maximum and minimum element present in the array after removing any subarray of size K. Examples: Input: arr[] = {4, 5, 8, 9, 1, 2}, K = 2Output: 4Explanation: Remove the subarray {8, 9}. The minimum difference between maximum and
10 min read
Minimize maximum difference between adjacent elements possible by removing a single array element
Given an sorted array arr[] consisting of N elements, the task is to find the minimum of all maximum differences between adjacent elements of all arrays obtained by removal of any single array element. Examples: Input: arr[ ] = { 1, 3, 7, 8}Output: 5Explanation:All possible arrays after removing a single element are as follows:{3, 7, 8}: Difference
6 min read
Minimize difference between maximum and minimum element of all possible subarrays
Given an array arr[ ] of size N, the task is to find the minimum difference between maximum and minimum elements of all possible sized subarrays of arr[ ]. Examples: Input: arr[] = { 5, 14, 7, 10 } Output: 3Explanation: {7, 10} is the subarray having max element = 10 & min element = 7, and their difference = 10 - 7 = 3 Input: arr[] = { 2, 6, 15
5 min read
Minimize difference between maximum and minimum element by decreasing and increasing Array elements by 1
Given an array arr[], consisting of N positive integers. The task is to minimize the difference between the maximum and the minimum element of the array by performing the below operation any number of times (possibly zero). In one operation choose 2 different index, i and j and decrement arr[i] and increment arr[j] by 1.Notice this operation can be
5 min read
Minimize difference between maximum and minimum Subarray sum by splitting Array into 4 parts
Given an array arr[] of size N, the task is to find the minimum difference between the maximum and the minimum subarray sum when the given array is divided into 4 non-empty subarrays. Examples: Input: N = 5, arr[] = {3, 2, 4, 1, 2}Output: 2Explanation: Divide the array into four parts as {3}, {2}, {4} and {1, 2}. The sum of all the elements of thes
14 min read
Minimize the maximum distance between adjacent points after adding K points anywhere in between
Given an array arr[] of N integers representing the position of N points along a straight line and an integer K, the task is to find the minimum value of the maximum distance between adjacent points after adding K points anywhere in between, not necessarily on an integer position. Examples: Input: arr[] = {2, 4, 8, 10}, K = 1Output: 2Explanation: A
9 min read
Minimize the maximum minimum difference after one removal from array
Given an array arr[] of size n ? 3, the task is to find the minimum possible difference between the maximum and the minimum element from the array after removing one element. Examples: Input: arr[] = {1, 2, 3} Output: 1 Removing 1 will give 3 - 2 = 1 Removing 2, 3 - 1 = 2 And removing 3 will result in 2 - 1 = 1 Input: arr[] = {1, 2, 4, 3, 4} Output
11 min read
Minimize the maximum absolute difference of adjacent elements in a circular array
Given a circular array arr of N integers, the task is to minimize the maximum absolute difference of adjacent elements of the array without any removals. Examples: Input: arr[] = {1, 3, 10, 2, 0, 9, 6} Output: {0, 2, 6, 10, 9, 3, 1} Explanation: In the above example, the maximum difference between adjacent elements is 6, which is between 9 and 3. O
6 min read
Minimize the maximum difference of adjacent elements after at most K insertions
Given an array of N elements, the task is to minimize the maximum difference of adjacent elements by inserting at most K elements in the array.Examples: Input: arr = [2, 6, 8] K = 1 Output: 2 Explanation: After insertion of 4 in between 2 and 6, the array becomes [2, 4, 6, 8]. In this case the maximum difference between any adjacent element is 2, w
7 min read
Minimize the maximum difference of any pair by doubling odd elements and reducing even elements by half
Given an array arr[] consisting of N positive integers, the task is to minimize the maximum difference between any pair of array elements by multiplying any odd array element by 2 and dividing any even array element by 2. Examples: Input: arr[] = {4, 1, 5, 20, 3}Output: 3Explanation:Operation 1: Multiplying arr[1] by 2 modifies arr[] to {4, 2, 5, 2
7 min read
Minimize maximum adjacent difference in a path from top-left to bottom-right
Given a matrix arr[][] of size M * N, where arr[i][j] represents the height of the cell (row, col). The task is to find a path from top-left to bottom-right such that the value of the maximum difference in height between adjacent cells is minimum for that path. Note: A path energy is the maximum absolute difference in heights between two consecutiv
12 min read
Minimize the maximum value of the absolute difference
Given array A[] of size N (1 <= N <= 105). The following operation should be performed until array A[] is not empty. choose three integers X, Y, and Z, Take out an element from array A[] (1 <= A[i] <= 109), and choose one integer out of the chosen three integers X, Y, and Z record absolute difference between them, then delete the elemen
10 min read
Minimize sum of differences between maximum and minimum elements present in K subsets
Given an array arr[] of size N and an integer K, the task is to minimize the sum of the difference between the maximum and minimum element of each subset by splitting the array into K subsets such that each subset consists of unique array elements only. Examples: Input: arr[] = { 6, 3, 8, 1, 3, 1, 2, 2 }, K = 4 Output: 6 Explanation: One of the opt
12 min read
Minimize the Maximum Distance between runners
Given two arrays dist[] and speed[] of size N (number of runners) and a positive integer T (duration of a race), where dist[i], speed[i] indicating the initial distance and speed of the ith runner from the starting line respectively. The task is to find the minimum distance between the two most distant runners at any time during the race. Note: The
8 min read
Maximum sum of a subsequence having difference between their indices equal to the difference between their values
Given an array A[] of size N, the task is to find the maximum sum of a subsequence such that for each pair present in the subsequence, the difference between their indices in the original array is equal to the difference between their values. Examples: Input: A[] = {10, 7, 1, 9, 10, 15}, N = 6Output: 26Explanation: Subsequence: {7, 9, 10}. Indices
5 min read
Maximum subset sum having difference between its maximum and minimum in range [L, R]
Given an array arr[] of N positive integers and a range [L, R], the task is to find the maximum subset-sum such that the difference between the maximum and minimum elements of the subset lies in the given range. Examples: Input: arr[] = {6, 5, 0, 9, 1}, L = 0, R = 3Output: 15Explanation: The subset {6, 9} of the given array has the difference betwe
9 min read
Minimize count of array elements to be removed to maximize difference between any pair up to K
Given an array arr[] and an integer K, the task is to count the number of elements to be removed from the array such that the difference of the maximum and the minimum number left does not exceed K. Examples: Input: K = 1, arr[] = {1, 2, 3, 4, 5} Output: 3 Explanation: Removal of {5, 4, 3} modifies array to {1, 2} where the maximum difference is 1(
5 min read
Minimize absolute difference between the smallest and largest array elements by minimum increment decrement operations
Given an array arr[] consisting of N positive integers, the task is to minimize the number of operations required to minimize the absolute difference between the smallest and largest elements present in the array. In each operation, subtract 1 from an array element and increment 1 to another array element. Examples: Input: arr[] = {1, 6}Output: 2Ex
8 min read
Minimize difference between the largest and smallest array elements by K replacements
Given an array A[] consisting of N integers, the task is to find the minimum difference between the largest and the smallest element in the given array after replacing K elements. Examples: Input: A[] = {-1, 3, -1, 8, 5, 4}, K = 3Output: 2Explanation:Replace A[0] and A[2] by 3 and 4 respectively. Replace A[3] by 5. Modified array A[] is {3, 3, 4, 5
12 min read
Minimize difference between two sequences obtained by splitting first N powers of 2
Given a positive even number N, the task is to split the first N powers of 2 into two equal sequences such that the absolute difference between their sum is minimized. Print the minimum difference obtained. Examples: Input: N = 2Output: 2Explanation:The sequence is {2, 4}.Only possible way to split the sequence is {2}, {4}. Therefore, difference =
5 min read
Article Tags :
Practice Tags :