#908
Easy Algorithms Smallest range i
Array Math
73.3% acceptance
Feb 25, 2026
787
2087
You are given an integer array nums and an integer k.
In one operation, you can choose any index i where 0 <= i < nums.length and change nums[i] to nums[i] + x where x is an integer from the range [-k, k]. You can apply this operation at most once for each index i.
The score of nums is the difference between the maximum and minimum elements in nums.
Return the minimum score of nums after applying the mentioned operation at most once for each index in it.
Solution
Rust
Time O(n)
Space O(1)
impl Solution {
pub fn smallest_range_i(nums: Vec<i32>, k: i32) -> i32 {
let (mn, mx) = (nums.iter().min().unwrap(), nums.iter().max().unwrap());
0.max(mx - mn - 2 * k)
}
}