Skip to content

Commit 11e0102

Browse files
committed
feat: solve No.910
1 parent ae96004 commit 11e0102

File tree

1 file changed

+83
-0
lines changed

1 file changed

+83
-0
lines changed

901-1000/910. Smallest Range II.md

Lines changed: 83 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,83 @@
1+
# 910. Smallest Range II
2+
3+
- Difficulty: Medium.
4+
- Related Topics: Array, Math, Greedy, Sorting.
5+
- Similar Questions: .
6+
7+
## Problem
8+
9+
You are given an integer array `nums` and an integer `k`.
10+
11+
For each index `i` where `0 <= i < nums.length`, change `nums[i]` to be either `nums[i] + k` or `nums[i] - k`.
12+
13+
The **score** of `nums` is the difference between the maximum and minimum elements in `nums`.
14+
15+
Return **the minimum **score** of **`nums`** after changing the values at each index**.
16+
17+
 
18+
Example 1:
19+
20+
```
21+
Input: nums = [1], k = 0
22+
Output: 0
23+
Explanation: The score is max(nums) - min(nums) = 1 - 1 = 0.
24+
```
25+
26+
Example 2:
27+
28+
```
29+
Input: nums = [0,10], k = 2
30+
Output: 6
31+
Explanation: Change nums to be [2, 8]. The score is max(nums) - min(nums) = 8 - 2 = 6.
32+
```
33+
34+
Example 3:
35+
36+
```
37+
Input: nums = [1,3,6], k = 3
38+
Output: 3
39+
Explanation: Change nums to be [4, 6, 3]. The score is max(nums) - min(nums) = 6 - 3 = 3.
40+
```
41+
42+
 
43+
**Constraints:**
44+
45+
46+
47+
- `1 <= nums.length <= 104`
48+
49+
- `0 <= nums[i] <= 104`
50+
51+
- `0 <= k <= 104`
52+
53+
54+
55+
## Solution
56+
57+
```javascript
58+
/**
59+
* @param {number[]} nums
60+
* @param {number} k
61+
* @return {number}
62+
*/
63+
var smallestRangeII = function(nums, k) {
64+
nums.sort((a, b) => a - b);
65+
var n = nums.length;
66+
var res = nums[n - 1] - nums[0];
67+
for (var i = 0; i < n - 1; i++) {
68+
var low = Math.min(nums[0] + k, nums[i + 1] - k);
69+
var high = Math.max(nums[n - 1] - k, nums[i] + k);
70+
res = Math.min(res, high - low);
71+
}
72+
return res;
73+
};
74+
```
75+
76+
**Explain:**
77+
78+
nope.
79+
80+
**Complexity:**
81+
82+
* Time complexity : O(n).
83+
* Space complexity : O(1).

0 commit comments

Comments
 (0)