Minimize the Heights II

Given an array arr[] denoting heights of N towers and a positive integer K, you have to modify the height of each tower either by increasing or decreasing them by K only once. After modifying, height should be a non-negative integer.
Find out the minimum possible difference of the height of shortest and longest towers after you have modified each tower.

You can find a slight modification of the problem here.
Note: It is compulsory to increase or decrease (if possible) by K to each tower.

Example 1:

Input:
K = 2, N = 4
Arr[] = {1, 5, 8, 10}
Output:
5
Explanation:
The array can be modified as
{3, 3, 6, 8}. The difference between
the largest and the smallest is 8-3 = 5.

Example 2:

Input:
K = 3, N = 5
Arr[] = {3, 9, 12, 16, 20}
Output:
11
Explanation:
The array can be modified as
{6, 12, 9, 13, 17}. The difference between
the largest and the smallest is 17-6 = 11.

class Solution {
    int getMinDiff(int[] a, int n, int k) {
        Arrays.sort(a);
        int max=0, min=0;
        int ans = a[n-1]-a[0];
        int lar = a[n-1]-k, sml = a[0]+k;
        
        for(int i=0;i<n-1;i++){
            min = Math.min(sml, a[i+1] - k);
            max = Math.max(lar, a[i] + k);
            if(min<0) continue;
            ans = Math.min(ans, max-min);
        }
        return ans;
    }
}
Comments (6)