LeetCode每日一题(1509. Minimum Difference Between Largest and Smallest Value in Three Moves)

给定一个整数数组nums,你可以选择一个元素并将其改变为任意值。求最多进行三次操作后,数组中最大值和最小值之间的最小差值。本文通过排序和动态规划的方法,讨论如何在不同情况下找到最优解。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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)
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值