Leetcode 910 smallest range II 缩小极值之间的间距

文章讨论了如何通过改变给定整数数组nums中每个元素加上或减去k,使得数组的最大值与最小值之差最小。通过排序和分区策略,提供了一种Solution类的实现方法来计算最小范围II。
摘要由CSDN通过智能技术生成

You are given an integer array nums and an integer k.

For each index i where 0 <= i < nums.length, change nums[i] to be either nums[i] + k or nums[i] - k.

The score of nums is the difference between the maximum and minimum elements in nums.

Return the minimum score of nums after changing the values at each index.

Example 1:

Input: nums = [1], k = 0
Output: 0
Explanation: The score is max(nums) - min(nums) = 1 - 1 = 0.
Example 2:

Input: nums = [0,10], k = 2
Output: 6
Explanation: Change nums to be [2, 8]. The score is max(nums) - min(nums) = 8 - 2 = 6.
Example 3:

Input: nums = [1,3,6], k = 3
Output: 3
Explanation: Change nums to be [4, 6, 3]. The score is max(nums) - min(nums) = 6 - 3 = 3.

Constraints:

1 <= nums.length <= 104
0 <= nums[i] <= 104
0 <= k <= 104


After sorting the array, if we want to minimize max-min by +k or -k, there’s a partition in the final sorted array where all the left items +k and all the right ones -k. It’s easy to demonstrate this by enumerate all situations. So the final code is:

class Solution:
    def smallestRangeII(self, nums: List[int], k: int) -> int:
        sorted_nums = sorted(nums)
        l = len(sorted_nums)
        res = sorted_nums[l-1]-sorted_nums[0]
        for i in range(l-1):
            candidate_min = min(sorted_nums[0]+k, sorted_nums[i+1]-k)
            candidate_max = max(sorted_nums[l-1]-k, sorted_nums[i]+k)
            res = min(res, candidate_max-candidate_min)
        return res
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值