# 一、题目描述

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


# 二、题解

## (1) 线性扫描：

• A[0]...A[i]
• A[i+1]...A[N-1]N为数组的元素的个数）

• 最大值：A[N-1]-k / A[i]+K
• 最小值：A[0]+K / A[i+1]-K

public int smallestRangeII(int[] A, int K) {
Arrays.sort(A);
int N = A.length;
int ans = A[N-1] - A[0];
int a = 0, b = 0;

for (int i = 0; i < N - 1; i++) {
a = A[i] + K;
b = A[i+1] - K;
int mayBeMax = Math.max(a, A[N-1]-K);
int mayBeMin = Math.min(b, A[0]+K);
ans = Math.min(ans, mayBeMax-mayBeMin);
}
return ans;
}


### 复杂度分析

• 时间复杂度：O(N logN);Max(O(N logN), O(N))，其中NA的长度。
• 空间复杂度：O(1)，只使用了常数级别的额外空间。

©️2019 CSDN 皮肤主题: 大白 设计师: CSDN官方博客