原题链接:Leetcode 908. Smallest Range I
You are given an integer array nums
and an integer k
.
In one operation, you can choose any index i
where 0 <= i < nums.length
and change nums[i]
to nums[i] + x
where x
is an integer from the range [-k, k]
. You can apply this operation at most once for each index i.
The score of nums
is the difference between the maximum and minimum elements in nums
.
Return the minimum score of nums
after applying the mentioned operation at most once for each index in it.
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: 0
Explanation: Change nums to be [4, 4, 4]. The score is max(nums) - min(nums) = 4 - 4 = 0.
Constraints:
- 1 <= nums.length <= 104
- 0 <= nums[i] <= 104
- 0 <= k <= 104
做法一:数学
思路:
我们总可以将当前的max-min
缩短为max-min-2k
。
当2k > max-min
时,总可以将他们都改成同一个数,实现最小差值为0
c++代码:
class Solution {
public:
int smallestRangeI(vector<int>& nums, int k) {
int min_n = INT_MAX, max_n = INT_MIN;
for(auto n : nums){
min_n = min(min_n, n);
max_n = max(max_n, n);
}
return max(0, max_n - min_n - 2 * k);
}
};
复杂度分析:
- 时间复杂度:O(n),遍历了一遍数组
- 空间复杂度:O(1),常数个临时变量