Given an array A of integers, for each integer A[i] we may choose any x with -K <= x <= K, and add x to A[i].
After this process, we have some array B.
Return the smallest possible difference between the maximum value of B and the minimum value of B.
Example 1:
Input: A = [1], K = 0
Output: 0
Explanation: B = [1]
Example 2:
Input: A = [0,10], K = 2
Output: 6
Explanation: B = [2,8]
Example 3:
Input: A = [1,3,6], K = 3
Output: 0
Explanation: B = [3,3,3] or B = [4,4,4]
Note:
1 <= A.length <= 10000
0 <= A[i] <= 10000
0 <= K <= 10000
这题其实有点绕,一开始想的很复杂,后来一想,只需要考虑最大值和最小值,其余不用考虑。
首先我们找出最小值和最大值,然后给最小值加上K,最大值减去K。假设第一个结果大于了第二个结果,说明它们可以加上某一个K使得它们相等。假设最小值和最大值都能相等了,那么中间的一些值加上或者减去更小的K就能得到之前相等的值了,所以这种情况下差值是0。
反之它们之间的差值就是本题想要的答案。因为其它的值肯定可以获得更小的差值。
class Solution {
public:
int smallestRangeI(vector<int>& A, int K) {
int maxv = A[0], minv = A[0];
for (auto v : A) {
maxv = std::max(maxv, v);
minv = std::min(minv, v);
}
int maxk = maxv - K;
int mink = minv + K;
if (mink >= maxk) {
return 0;
}
return maxk - mink;
}
};