题目
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
链接
https://leetcode.com/problems/smallest-range-i/
分析
A的最大值和最小值之间的diff,如果在[0, 2K]之间,那么一定可以调成一个所有元素都相等的数组;
否则可想办法消去这个2K的diff
代码
class Solution(object):
"""
A的最大值和最小值之间的diff,如果在[0, 2K]之间,那么一定可以调成一个所有元素都相等的数组;
否则可想办法消去这个2K的diff
"""
def smallestRangeI(self, A, K):
"""
:type A: List[int]
:type K: int
:rtype: int
"""
min = 10000
max = 0
for ele in A:
if ele < min:
min = ele
if ele > max:
max = ele
diff = max - min
if diff >= 0 and diff < 2*K:
return 0
else:
return diff - 2*K