Intuition
Changing two elements lets you always force the low score to zero (make two values equal), so you only need to minimize the high score (max minus min) by neutralizing two of the four outermost values.
Explanation
Key idea
You may change two elements to any values. Two independent things decide the score:
- low score = the smallest gap between any two numbers.
- high score = the largest gap, which for a set is always
max - min.
Because you can set a changed element to any value, you can always make two elements equal, which forces the low score to 0. So the low score is never a problem: the answer is the smallest high score you can reach by spending your two changes.
Minimizing the high score
The high score is max - min. To shrink it you want to pull in the extremes. With two changes you remove two of the outermost values and let the spread be decided by whatever is left. Sort the array; the useful spend is on the two smallest, the two largest, or one from each side. That leaves exactly three candidate spreads:
- Change the two smallest → spread
nums[n-1] - nums[2]. - Change the two largest → spread
nums[n-3] - nums[0]. - Change the largest and the smallest → spread
nums[n-2] - nums[1].
The answer is the minimum of these three (the low score is 0, so nothing is added).
Walk-through: nums = [1,4,7,8,5]
Sort → [1,4,5,7,8], n = 5.
- Change two smallest (1 and 4): spread
nums[4] - nums[2] = 8 - 5 = 3. - Change two largest (7 and 8): spread
nums[2] - nums[0] = 5 - 1 = 4. - Change one of each (1 and 8): spread
nums[3] - nums[1] = 7 - 4 = 3.
Minimum spread = 3. Low score is 0 (e.g. make the two changed values equal), so the score = 3 + 0 = 3.
Why only the ends matter
The middle values can never be the max or the min of the final set once you have options at the ends, so spending a change on a middle element can never shrink max - min more than spending it on an extreme. Trimming from the ends dominates every other move.
Complexity
- Time: O(n log n) for the sort; the rest is O(1).
- Space: O(1) beyond the sort.
Implementation
class Solution {
public int minimizeSum(int[] nums) {
Arrays.sort(nums);
int n = nums.length;
// Low score can always be forced to 0 by making two elements equal.
// Minimize the high score (max - min) by trimming two of the extremes.
int a = nums[n - 1] - nums[2]; // change the two smallest
int b = nums[n - 3] - nums[0]; // change the two largest
int c = nums[n - 2] - nums[1]; // change one smallest and one largest
return Math.min(a, Math.min(b, c));
}
}