Description:
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:
Example 2:
Example 3:
Note:
- 1 <= A.length <= 10000
- 0 <= A[i] <= 10000
- 0 <= K <= 10000
题意:给定一个一维数组A和一个整数K,现要求利用A和K得到数组B,数组B中的元素B[i] = A[i] + k(-K <= k <= K),使得返回的数组B中元素最大值与最小值的差最小;
解法:我们现在关心的知识令数组B中最大值与最小值的差最小,因此,对于A来说我们需要考虑的也仅仅是最大值max与最小值min(只有这两个值会影响最终的结果);
- 如果max - min <= 2 * K,那么说明我们可以利用K令A中的最小值和最大值相等
- 如果max - min > 2 * K,那么我们只能利用K令A中的最小值与最大值尽量接近
Java