Input: nums =[5,3,2,4]Output: 0Explanation: We can make at most 3 moves.In the first move, change 2 to 3. nums becomes [5,3,3,4].In the second move, change 4 to 3. nums becomes [5,3,3,3].In the third move, change 5 to 3. nums becomes [3,3,3,3].After performing 3 moves, the difference between the minimum and maximum is3-3=0.
Example 2:
1
2
3
4
5
6
7
8
Input: nums =[1,5,0,10,14]Output: 1Explanation: We can make at most 3 moves.In the first move, change 5 to 0. nums becomes [1,0,0,10,14].In the second move, change 10 to 0. nums becomes [1,0,0,0,14].In the third move, change 14 to 1. nums becomes [1,0,0,0,1].After performing 3 moves, the difference between the minimum and maximum is1-0=1.It can be shown that there is no way to make the difference 0in3 moves.
Example 3:
1
2
3
4
5
6
7
Input: nums =[3,100,20]Output: 0Explanation: We can make at most 3 moves.In the first move, change 100 to 7. nums becomes [3,7,20].In the second move, change 20 to 7. nums becomes [3,7,7].In the third move, change 3 to 7. nums becomes [7,7,7].After performing 3 moves, the difference between the minimum and maximum is7-7=0.
If we have a sorted array, say in ascending order, we can see the difference between the elements is between elements at 0 and n - 1 index, where n is length of the array. But, here we have 3 moves given to us where we can change these values, to reduce this difference. For eg. we can make the largest 3 elements equal to smallest element.
Now, we have 4 plans:
Remove the 3 largest elements.
Remove the 2 largest elements and the smallest element.
Remove the largest element and the 2 smallest elements.
classSolution {
publicintminDifference(int[] nums) {
int n = nums.length;
// If array has 4 or fewer elements, return 0 difference (all elements can be made equal)if (n <= 4) {
return 0;
}
Arrays.sort(nums);
int ans = nums[n - 1]- nums[0];
for (int i = 0; i <= 3; i++) {
ans = Math.min(ans, nums[n - 1 - (3 - i)]- nums[i]);
}
return ans;
}
}
Similar result can be obtained by storing the values in max and min heap, and get the results. We can just store 4 elements in both max and min heap, and calculate the values accordingly.
We only need the first four smallest and the last four largest numbers, thus sorting the entire array is unnecessary. Instead, we can use an array of size 4 to keep track of the top 4 smallest and top 4 largest elements.