版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_24133491/article/details/82820950
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:
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
题意:给定一个一维数组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
class Solution {
public int smallestRangeI(int[] A, int K) {
int min = A[0];
int max = A[0];
for (int x : A) {
min = x < min ? x : min;
max = x > max ? x : max;
}
return max - min <= 2 * K ? 0 : max - min - 2 * K;
}
}