Minimum Difference Between Largest and Smallest Value in Three Moves Problem
Description
LeetCode Problem 1509.
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 <= 10^5-10^9 <= nums[i] <= 10^9
Solution
Approach: Sort and Try Four Windows
A move can set a number to anything, so the best use of a move is to change an extreme number into one of the values we keep. Changed numbers then never affect the minimum or the maximum. Three moves therefore mean: throw away three numbers and minimize max - min of the rest.
Throwing away numbers from the middle never helps, so we remove l of the smallest and 3 - l of the largest, for l = 0, 1, 2, 3. After sorting, the numbers we keep are the window nums[l .. n - 4 + l], and its spread is nums[n - 4 + l] - nums[l]. The answer is the smallest of these four values.
If n <= 4, three moves can turn all but one number into that number, so the answer is 0. This check is also needed so that the window indices stay inside the array.
Complexity: O(n log n) time for sorting and O(1) extra space besides the sort. (Finding only the four smallest and four largest values would make it O(n).)
class Solution:
def minDifference(self, nums: List[int]) -> int:
n = len(nums)
if n <= 4:
return 0 # change all but one number to that number
nums.sort()
# change the l smallest and the 3 - l largest numbers
return min(nums[n - 4 + l] - nums[l] for l in range(4))