[LeetCode] Smallest Range II

910. Smallest Range II

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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
class Solution {
public:
int smallestRangeII(vector<int>& A, int K) {
sort(A.begin(), A.end());
int res = A.back() - A.front();
for (int i = 0; i < A.size() - 1; i++) {
int hi = max(A.back() - K, A[i] + K);
int lo = min(A.front() + K, A[i + 1] - K);
res = min(res, hi - lo);
}

return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2021/02/10/PS/LeetCode/smallest-range-ii/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.