Given an arrayAof integers, for each integerA[i]we may choose anyxwith-K <= x <= K, and addxtoA[i].

After this process, we have some arrayB.

Return the smallest possible difference between the maximum value ofB and the minimum value ofB.

Note:

  1. 1 <= A.length <= 10000
  2. 0 <= A[i] <= 10000
  3. 0 <= K <= 10000

这道题需要求出每个元素变化之后的范围,然后按照范围排序,起点和终点最小的范围的最大值,和起点终点最大的范围的最小值比较,如果最大值比最小值更大,说明范围有重叠,返回0,否则返回两个数的差值。

由于变化之后的范围由元素本身和一个固定的数K相关,所以其实排序的部分可以省略,直接找出数组中的最大最小值,如果min + K > max - K,返回0,否则返回max - K - min - K

class Solution {
    public int smallestRangeI(int[] A, int K) {
        if(A == null || A.length <= 1)
            return 0;

        int min = A[0];
        int max = A[0];

        for(int i = 1; i < A.length; i++) {
            min = Math.min(min, A[i]);
            max = Math.max(max, A[i]);
        }

        return max - K < min + K ? 0 : max - min - K - K;
    }
}

results matching ""

    No results matching ""