参考
https://blog.csdn.net/zjucor/article/details/82820938
题目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
代码
class Solution(object):
def smallestRangeII(self, A, K):
"""
:type A: List[int]
:type K: int
:rtype: int
"""
if len(A) <= 0:
return 0
A.sort() ## 给A按照从小到大的顺序排序
res = A[-1] - A[0]
## 最优解一定是左边一部分全往右,剩下的右边全部往左,不管2边是否会越对方的界限
## 数组B中最小值肯定是(A[0] + K) 与 (A[i + 1] - K)中的较小者,
## 数组B中最大值肯定是(A[i] + K) 与 (A[-1] - K)中的较大着
for i in range(0, len(A) - 1):
min_val = min(A[0] + K, A[i + 1] - K)
max_val = max(A[i] + K, A[-1] - K)
res = min(res, max_val - min_val)
return res