解题思路:
首先找到最大值和最小值,因为只有在这两个数上操作才是最小结果,如果二者差值小于2k,直接返回0,否则返回二者差值再减去2k,代码如下:
class Solution {
public:
int smallestRangeI(vector<int>& nums, int k) {
int maxNum = *max_element(nums.begin(), nums.end());
int minNum = *min_element(nums.begin(), nums.end());
return maxNum - minNum >= 2 * k ? maxNum - minNum - 2 * k : 0;
}
};