Skip to content

Commit 03d12d1

Browse files
committed
day 21
1 parent 02ad8a9 commit 03d12d1

File tree

2 files changed

+51
-1
lines changed

2 files changed

+51
-1
lines changed
Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
/*
2+
Smallest Range II
3+
=================
4+
5+
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).
6+
7+
After this process, we have some array B.
8+
9+
Return the smallest possible difference between the maximum value of B and the minimum value of B.
10+
11+
Example 1:
12+
Input: A = [1], K = 0
13+
Output: 0
14+
Explanation: B = [1]
15+
16+
Example 2:
17+
Input: A = [0,10], K = 2
18+
Output: 6
19+
Explanation: B = [2,8]
20+
21+
Example 3:
22+
Input: A = [1,3,6], K = 3
23+
Output: 3
24+
Explanation: B = [4,6,3]
25+
26+
Note:
27+
1 <= A.length <= 10000
28+
0 <= A[i] <= 10000
29+
0 <= K <= 10000
30+
*/
31+
32+
class Solution
33+
{
34+
public:
35+
int smallestRangeII(vector<int> &A, int K)
36+
{
37+
sort(A.begin(), A.end());
38+
int ans = -A[0] + A[A.size() - 1];
39+
for (int i = 0; i < A.size() - 1; ++i)
40+
{
41+
int j = i + 1;
42+
int low = min(A[0] + K, A[j] - K);
43+
int high = max(A[A.size() - 1] - K, A[i] + K);
44+
ans = min(ans, high - low);
45+
}
46+
return ans;
47+
}
48+
};

Leetcode Daily Challenge/December-2020/README.md

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -20,4 +20,6 @@
2020
| 16. | [Validate Binary Search Tree](https://leetcode.com/explore/challenge/card/december-leetcoding-challenge/571/week-3-december-15th-december-21st/3568/) | [cpp](./16.%20Validate%20Binary%20Search%20Tree.cpp) |
2121
| 17. | [4Sum II](https://leetcode.com/explore/challenge/card/december-leetcoding-challenge/571/week-3-december-15th-december-21st/3569/) | [cpp](./17.%204Sum%20II.cpp) |
2222
| 18. | [Increasing Triplet Subsequence](https://leetcode.com/explore/challenge/card/december-leetcoding-challenge/571/week-3-december-15th-december-21st/3570/) | [cpp](./18.%20Increasing%20Triplet%20Subsequence.cpp) |
23-
| 19. | [Cherry Pickup II](https://leetcode.com/explore/challenge/card/december-leetcoding-challenge/571/week-3-december-15th-december-21st/3571/) | [cpp](./19.%20Cherry%20Pickup%20II.cpp)
23+
| 19. | [Cherry Pickup II](https://leetcode.com/explore/challenge/card/december-leetcoding-challenge/571/week-3-december-15th-december-21st/3571/) | [cpp](./19.%20Cherry%20Pickup%20II.cpp) |
24+
| 20. | []() |[cpp](./20.%20.cpp) |
25+
| 21. | [Smallest Range II](https://leetcode.com/explore/challenge/card/december-leetcoding-challenge/571/week-3-december-15th-december-21st/3573/) |[cpp](./21.%20Smallest%20Range%20II.cpp) |

0 commit comments

Comments
 (0)