VOOZH about

URL: https://www.geeksforgeeks.org/dsa/minimize-the-maximum-difference-between-the-heights/

⇱ Minimize the maximum difference between the heights - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Minimize the maximum difference between the heights

Last Updated : 6 Sep, 2025

Given an array arr[] representing the heights of towers and a positive integer k, we can modify each tower’s height exactly once by either adding k or subtracting k. After these modifications, find the minimum possible difference between the tallest and the shortest tower.

Note: It is compulsory to increase or decrease the height by k for each tower. After the operation, the resultant array should not contain any negative integers.

Examples: 

Input: k = 2, arr[] = [1, 5, 8, 10]
Output: 5
Explanation: The array can be modified as [1+k, 5-k, 8-k, 10-k]= [3, 3, 6, 8]. The difference between the largest and the smallest is 8 - 3 = 5.

Input: k = 3, arr[] = [3, 9, 12, 16, 20]
Output: 11
Explanation: The array can be modified as [3+k, 9+k, 12-k, 16-k, 20-k] = [6, 12, 9, 13, 17]. The difference between the largest and the smallest is 17 - 6 = 11.

[Approach] Using Sorting - O(n logn) Time and O(1) Space

We bring the towers closer by increasing the shorter ones and decreasing the taller ones. After sorting, we try splitting the array at some point: towers on the left are increased by +k, and towers on the right are decreased by -k.

Why this works:
The new minimum and maximum can only come from these boundaries. So by checking all split points, we cover every case and guarantee the minimum possible difference.

Steps to solve the problem:

  • Sort the array arr in non-decreasing order.
  • Initialize ans = arr[n-1] - arr[0].
  • Precompute smallest = arr[0] + k and largest = arr[n-1] - k.
  • Loop for i = 1 to n-1:
    => If arr[i] - k < 0, continue (heights can’t be negative).
    => minH = min(smallest, arr[i] - k).
    => maxH = max(largest, arr[i-1] + k).
    => ans = min(ans, maxH - minH).
  • Return ans.

Output
5
Comment
Article Tags: