#910
Medium Algorithms Smallest range ii
Array Math Greedy Sorting
37.7% acceptance
Feb 25, 2026
1711
468
You are given an integer array nums and an integer k.
For each index i where 0 <= i < nums.length, change nums[i] to be either nums[i] + k or nums[i] - k.
The score of nums is the difference between the maximum and minimum elements in nums.
Return the minimum score of nums after changing the values at each index.
Solution
Rust
Time O(n log n)
Space O(1)
impl Solution {
pub fn smallest_range_ii(mut nums: Vec<i32>, k: i32) -> i32 {
nums.sort();
let n = nums.len();
let mut ans = nums[n-1] - nums[0];
for i in 0..n-1 {
let hi = (nums[i] + k).max(nums[n-1] - k);
let lo = (nums[0] + k).min(nums[i+1] - k);
ans = ans.min(hi - lo);
}
ans
}
}