Minimise the maximum difference between heights

Pattern: Traversal and in-place tricks

easy

Every tower must go up or down by k. After sorting, the best plan raises a prefix and lowers the rest, so try every split point.

No verified practice link yet. The guide below states the problem in full, so you can still solve it here.

The problem

You are given the heights of between 1 and 100,000 towers and a number k. Every tower must change by exactly k: either up by k or down by k. No height may become negative. Choose the changes so that the difference between the tallest and shortest tower is as small as possible, and return that difference. For example, with heights [1, 5, 8, 10] and k = 2, the best result is 5 (for example 3, 3, 6, 8).

This problem is from Love Babbar's 450 sheet, and this guide has no verified link for it yet. The function name getMinDiff, the "never negative" rule and the limits are this guide's own; versions of this problem online differ on that rule, so read your platform's statement.

Think first

  • With n towers there are 2ⁿ ways to choose up or down. Can you rule most of them out?
  • After sorting, would it ever make sense to raise a tall tower and lower a shorter one?
  • If the first few towers go up and the rest go down, which four values decide the new lowest and highest?

Hints

    Brute force, and why it fails

    Try all 2ⁿ up/down choices and keep the smallest gap among those with no negative heights. That is correct and is what this guide's tests are checked against for small inputs, but for 20 towers it is already a million choices, and 100,000 towers is impossible.

    The key insight

    Once the heights are sorted, only "raise a prefix, lower the rest" plans can be best. There are just n - 1 such splits, and each is checked in O(1) using the four towers at its edges.

    Dry run

    10 
    51 
    82 
    103 
    k2
    best9

    arr = [1, 5, 8, 10] (already sorted) and k = 2. If every tower moves the same way, the gap stays 10 - 1 = 9. That is the first candidate.

    Step 1 of 5

    The plan

    sort arr
    best = arr[n - 1] - arr[0]           # everyone moves the same way
    for i from 1 to n - 1:
        if arr[i] - k < 0:
            continue                     # a height would go negative
        low = min(arr[0] + k, arr[i] - k)
        high = max(arr[i - 1] + k, arr[n - 1] - k)
        best = min(best, high - low)
    return best
    

    Complexity

    Time
    O(n log n)
    Space
    O(1)

    The sort dominates. The split loop is O(n). Sorting in place needs no extra array (the library sort may use a little memory of its own).

    Edge cases

    • One tower: the gap is 0, and the starting value arr[0] - arr[0] already gives it.
    • Equal towers, as in [4, 4] with k = 3: moving both the same way keeps the gap at 0.
    • A huge k, as in [1, 2] with k = 10: lowering is impossible, so both go up and the gap stays 1.
    I've built my logic, show the code

    Java

    import java.util.*;
    
    class Solution {
        public int getMinDiff(int[] arr, int k) {
            int n = arr.length;
            Arrays.sort(arr);
            int best = arr[n - 1] - arr[0];             // everyone +k, or everyone -k where possible
            for (int i = 1; i < n; i++) {
                // towers 0..i-1 go up by k, towers i..n-1 go down by k
                if (arr[i] - k < 0) {
                    continue;                           // a height would go negative
                }
                int low = Math.min(arr[0] + k, arr[i] - k);
                int high = Math.max(arr[i - 1] + k, arr[n - 1] - k);
                best = Math.min(best, high - low);
            }
            return best;
        }
    }

    C++

    class Solution {
    public:
        int getMinDiff(vector<int>& arr, int k) {
            int n = static_cast<int>(arr.size());
            sort(arr.begin(), arr.end());
            int best = arr[n - 1] - arr[0];             // everyone +k, or everyone -k where possible
            for (int i = 1; i < n; i++) {
                // towers 0..i-1 go up by k, towers i..n-1 go down by k
                if (arr[i] - k < 0) {
                    continue;                           // a height would go negative
                }
                int low = min(arr[0] + k, arr[i] - k);
                int high = max(arr[i - 1] + k, arr[n - 1] - k);
                best = min(best, high - low);
            }
            return best;
        }
    };

    Python

    class Solution:
        def getMinDiff(self, arr, k):
            n = len(arr)
            arr.sort()
            best = arr[n - 1] - arr[0]                  # everyone +k, or everyone -k where possible
            for i in range(1, n):
                # towers 0..i-1 go up by k, towers i..n-1 go down by k
                if arr[i] - k < 0:
                    continue                            # a height would go negative
                low = min(arr[0] + k, arr[i] - k)
                high = max(arr[i - 1] + k, arr[n - 1] - k)
                best = min(best, high - low)
            return best

    Common mistakes

    • Forgetting to sort first, which breaks the split argument.
    • Taking only arr[0] + k and arr[n-1] - k as the extremes and ignoring the two towers at the split.
    • Allowing negative heights, or forgetting the starting answer arr[n-1] - arr[0].

    Similar problems