![]() |
VOOZH | about |
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.
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:
5