Given an array A
of integers, for each integer A[i]
we need to choose either x = -K
or x = K
, and add x
to A[i] (only once)
.
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: 3 Explanation: B = [4,6,3]
Note:
1 <= A.length <= 10000
0 <= A[i] <= 10000
0 <= K <= 10000
题目大意:给定一个数组和一个数值K,数组中的每个值必须加上K或者减去K,求出操作之后最大值和最小值可能差值的最小值。
每个数值必须加上K或者减去K,可以简化为每个数值必须加上0或者加上2*K。
先对数组进行排序,然后从小到大每个元素依次加上2*K,更新最大值,最小值和差值,代码如下
public int smallestRangeII(int[] A, int K) {
Arrays.sort(A);
int min=A[0];
int len=A.length;
int max=A[len-1];
int ans=max-min;
for(int i=0;i<len-1;i++){
max=Math.max(A[i]+2*K,max);
min=Math.min(A[0]+2*K,A[i+1]);
ans=Math.min(ans,max-min);
}
return ans;
}
比较难理解的可能是这句min=Math.min(A[0]+2*K,A[i+1]);
每个元素依次加上2*K之后,如果A[i]+2*K小于A[i+1],则对于数组i左边的所有元素,加上2*K也仍然是小于A[i+1],所以此时的最小值为A[0]+2*K,但如果A[i]+2*K大于A[i+1]的话,此时的最小值可能为A[0]+2*K,也可能是A[i+1]。