Skip to content
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Commit 147f4c0

Browse files
committedMar 24, 2025
Add solution #910
1 parent 65cb1b5 commit 147f4c0

File tree

2 files changed

+34
-0
lines changed

2 files changed

+34
-0
lines changed
 

‎README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -720,6 +720,7 @@
720720
907|[Sum of Subarray Minimums](./solutions/0907-sum-of-subarray-minimums.js)|Medium|
721721
908|[Smallest Range I](./solutions/0908-smallest-range-i.js)|Easy|
722722
909|[Snakes and Ladders](./solutions/0909-snakes-and-ladders.js)|Medium|
723+
910|[Smallest Range II](./solutions/0910-smallest-range-ii.js)|Medium|
723724
912|[Sort an Array](./solutions/0912-sort-an-array.js)|Medium|
724725
914|[X of a Kind in a Deck of Cards](./solutions/0914-x-of-a-kind-in-a-deck-of-cards.js)|Medium|
725726
916|[Word Subsets](./solutions/0916-word-subsets.js)|Medium|

‎solutions/0910-smallest-range-ii.js

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
/**
2+
* 910. Smallest Range II
3+
* https://leetcode.com/problems/smallest-range-ii/
4+
* Difficulty: Medium
5+
*
6+
* You are given an integer array nums and an integer k.
7+
*
8+
* For each index i where 0 <= i < nums.length, change nums[i] to be either
9+
* nums[i] + k or nums[i] - k.
10+
*
11+
* The score of nums is the difference between the maximum and minimum elements
12+
* in nums.
13+
*
14+
* Return the minimum score of nums after changing the values at each index.
15+
*/
16+
17+
/**
18+
* @param {number[]} nums
19+
* @param {number} k
20+
* @return {number}
21+
*/
22+
var smallestRangeII = function(nums, k) {
23+
nums.sort((a, b) => a - b);
24+
25+
let result = nums[nums.length - 1] - nums[0];
26+
for (let i = 0; i < nums.length - 1; i++) {
27+
const high = Math.max(nums[nums.length - 1] - k, nums[i] + k);
28+
const low = Math.min(nums[0] + k, nums[i + 1] - k);
29+
result = Math.min(result, high - low);
30+
}
31+
32+
return result;
33+
};

0 commit comments

Comments
 (0)
Please sign in to comment.