力扣10.21-代码

时间:2024-10-22 18:55:51
typedef long long LL;
class Solution {
public:
    int smallestRangeII(vector<int>& nums, int k) {
        int maxx = 0, minx = 0;
        int n = nums.size();
        sort(nums.begin(), nums.end());
        int res = nums[n - 1] - nums[0];
        for(int i = 0; i < n - 1; i ++ ) {
            maxx = max(nums[i] + k, nums[n - 1] - k);
            minx = min(nums[0] + k, nums[i + 1] - k);
            res = min(res, maxx - minx);
        }
        return res;
    }
};