题目

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:

  1. Input: A = [1], K = 0
  2. Output: 0
  3. Explanation: B = [1]

Example 2:

  1. Input: A = [0,10], K = 2
  2. Output: 6
  3. Explanation: B = [2,8]

Example 3:

  1. Input: A = [1,3,6], K = 3
  2. Output: 3
  3. Explanation: B = [4,6,3]

Note:

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

题意

遍历一个数组,对每个值进行加K或减K的操作,求得到的新数组中(max-min)的最小值。

思路

因为每个元素都必须加K或者减K,可以将数组分成两组,一组全加K,一组全减K,很明显要让小的数加K,让大的数减K。因此可以先对数组排序,然后确定一个分界点,让左边的子数组left全部加K,右边的子数组right全部减K;同时注意到,两个子数组中的最小值都是各自的第一个元素,最大值都是各自的最后一个元素,因此可以比较得出全局的最大值和最小值,再以此更新结果。


代码实现

Java

  1. class Solution {
  2. public int smallestRangeII(int[] A, int K) {
  3. int ans = Integer.MAX_VALUE;
  4. Arrays.sort(A);
  5. for (int len = 0; len <= A.length; len++) {
  6. int max = 0, min = 0;
  7. if (len == 0 || len == A.length) {
  8. max = A[A.length - 1];
  9. min = A[0];
  10. } else {
  11. max = Math.max(A[len - 1] + K, A[A.length - 1] - K);
  12. min = Math.min(A[0] + K, A[len] - K);
  13. }
  14. ans = Math.min(ans, max - min);
  15. }
  16. return ans;
  17. }
  18. }