Skip to content

Commit 88930c8

Browse files
committed
[NEW][Array] 910. Smallest Range II
1 parent 94a7425 commit 88930c8

File tree

2 files changed

+58
-0
lines changed

2 files changed

+58
-0
lines changed
Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
Time spent : 15min(have little thought, see hint)
2+
3+
GIVEN: 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)**`.
4+
5+
After this process, we have some array `B`.
6+
7+
RETURNS: the smallest possible difference between the maximum value of `B` and the minimum value of `B`.
8+
9+
EXAMPLES:
10+
11+
**Example 1:**
12+
13+
```
14+
Input: A = [1], K = 0
15+
Output: 0
16+
Explanation: B = [1]
17+
```
18+
19+
**Example 2:**
20+
21+
```
22+
Input: A = [0,10], K = 2
23+
Output: 6
24+
Explanation: B = [2,8]
25+
```
26+
27+
**Example 3:**
28+
29+
```
30+
Input: A = [1,3,6], K = 3
31+
Output: 3
32+
Explanation: B = [4,6,3]
33+
```
34+
35+
Algorithm:
36+
37+
For an array like [1, 3, 4, 7], we can somewhat split the array into two parts, one parts all add K, one parts all subtract K, like (1, 3) + K, (4, 7) - K. For every this split, we can get max - min.
38+
39+
We sort the array first. Then we traverse the array from index 0 to N - 2, a = A[i], b = A[i + 1]. So the max is a + K, or A[N - 1] - K, same for min, is b - K or A[0] + K. Every time we compare the max - min with our ans and choose the smallest one.
Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
class Solution {
2+
public int smallestRangeII(int[] A, int K) {
3+
int N = A.length;
4+
Arrays.sort(A);
5+
int max = A[N - 1];
6+
int min = A[0];
7+
int ans = max - min;
8+
9+
for (int i = 0; i < N - 1; i++) {
10+
int a = A[i];
11+
int b = A[i + 1];
12+
max = Math.max(a + K, A[N - 1] - K);
13+
min = Math.min(b - K, A[0] + K);
14+
ans = Math.min(ans, max - min);
15+
}
16+
17+
return ans;
18+
}
19+
}

0 commit comments

Comments
 (0)