Problem
You are given an integer array nums
.
In one move, you can choose one element of nums
and change it to any value.
Return **the minimum difference between the largest and smallest value of nums
*after performing at most three moves***.
Example 1:
Input: nums = [5,3,2,4]
Output: 0
Explanation: 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 is 3 - 3 = 0.
Example 2:
Input: nums = [1,5,0,10,14]
Output: 1
Explanation: 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 is 1 - 0 = 1.
It can be shown that there is no way to make the difference 0 in 3 moves.
Example 3:
Input: nums = [3,100,20]
Output: 0
Explanation: 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 is 7 - 7 = 0.
Constraints:
1 <= nums.length <= 105
-109 <= nums[i] <= 109
Solution
/**
* @param {number[]} nums
* @return {number}
*/
var minDifference = function(nums) {
if (nums.length <= 4) return 0;
nums.sort((a, b) => a - b);
return Math.min(
nums[nums.length - 4] - nums[0],
nums[nums.length - 3] - nums[1],
nums[nums.length - 2] - nums[2],
nums[nums.length - 1] - nums[3],
);
};
Explain:
nope.
Complexity:
- Time complexity : O(n * log(n)).
- Space complexity : O(n).
Solution 2
/**
* @param {number[]} nums
* @return {number}
*/
var minDifference = function(nums) {
if (nums.length <= 4) return 0;
var minQueue = new MinPriorityQueue();
var maxQueue = new MaxPriorityQueue();
for (var i = 0; i < nums.length; i++) {
minQueue.enqueue(nums[i], nums[i]);
if (minQueue.size() > 4) {
minQueue.dequeue();
}
maxQueue.enqueue(nums[i], nums[i]);
if (maxQueue.size() > 4) {
maxQueue.dequeue();
}
}
const arr = [
...maxQueue.toArray().map(item => item.element).reverse(),
...minQueue.toArray().map(item => item.element),
];
return Math.min(
arr[arr.length - 4] - arr[0],
arr[arr.length - 3] - arr[1],
arr[arr.length - 2] - arr[2],
arr[arr.length - 1] - arr[3],
);
};
Explain:
nope.
Complexity:
- Time complexity : O(n * log(4) * log(4)) = O(n).
- Space complexity : O(1).