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 = 0.
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 [4,7,20].
In the second move, change 20 to 7. nums becomes [4,7,7].
In the third move, change 4 to 3. 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
将 nums 排序, 然后用 dp 来算每一步移除 nums 中最大值或者最小值, 三步之后的 nums 中的最大值和最小值的差。之所以是移除而不是直接赋值, 是因为实际最后的答案只跟移除 3 个值后 nums 中所剩的数字数量有关。如果剩余 0 个, 则证明 nums 原有的数字数量<3, 那我们只要把这些数字都改为任意一个数字,那答案就是 0.如果剩余 1 个,也差不多, 我们只需要把移除的 3 个数字都改成剩余的这个数字,答案还是 0。如果剩余 2 个及以上, 那我们的最优解就是把那 3 个移除的数字改成这 2 个剩余数字中间的任意值,最终的答案也就是这 2 个剩余数字的差值。
impl Solution {
fn dp(nums: &Vec<i32>, i: usize, j: usize, count: usize) -> i32 {
if i == j {
return 0;
}
if count == 0 {
return nums[j] - nums[i];
}
let change_min = Solution::dp(nums, i + 1, j, count - 1);
let change_max = Solution::dp(nums, i, j - 1, count - 1);
change_min.min(change_max)
}
pub fn min_difference(mut nums: Vec<i32>) -> i32 {
nums.sort();
Solution::dp(&nums, 0, nums.len() - 1, 3)
}
}