> For the complete documentation index, see [llms.txt](https://dfine.gitbook.io/leetcode/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://dfine.gitbook.io/leetcode/910.smallest_range_ii.md).

# 910.Smallest Range II

**910.Smallest Range II**

> 给定一个整数数组 A，对于每个整数 A\[i]，我们可以选择 x = -K 或是 x = K，并将 x 加到 A\[i] 中。 在此过程之后，我们得到一些数组 B。 返回 B 的最大值和 B 的最小值之间可能存在的最小差值。

```
 示例 1：

 输入：A = [1], K = 0
 输出：0
 解释：B = [1]
 示例 2：

 输入：A = [0,10], K = 2
 输出：6
 解释：B = [2,8]
 示例 3：

 输入：A = [1,3,6], K = 3
 输出：3
 解释：B = [4,6,3]
  
提示：

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

方法：可以先把数组排序，然后将数组看做两个部分，一部分是-K，一部分是+K。从头开始遍历，临界点之前的-K，临界点之后的+K，然后比较第一位+K和临界点右侧第一个-K的大小去最小值，以及最后一位-K后和临界点左边第一位+K后的大小取最大值，求出最大值与最小值的差。遍历一遍临界值，找出最小差值即可。

```
class Solution {
public:
  int smallestRangeII(vector<int>& A, int K) {
      sort(begin(A),end(A));
      int result=A.back()-A.front();
    
      for(int i=1;i<A.size();i++)
      {
         int l=min(A[0]+K,A[i]-K);
         int h=max(A.back()-K,A[i-1]+K);
          result = min(result,h-l);
      }
      return result;
  }
};
```


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

```
GET https://dfine.gitbook.io/leetcode/910.smallest_range_ii.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
