Leetcode 908. Smallest Range I
You are given an integer array nums
and an integer k
. In one operation, you can choose any element in nums
and add or subtract k
from it. The task is to return the smallest possible difference between the maximum and minimum elements of the array nums
after performing this operation any number of times for each element.
k
?
nums
will have at least one element, and k
is a non-negative integer.minNum
) and maximum (maxNum
) of the array.x
are in the range [x - k
, x + k
].newMax
) is maxNum - k
and the largest possible minimum value (newMin
) is minNum + k
.newMax - newMin
, but it should not be less than zero (as the range cannot be negative).```java public class SmallestRangeI { public int smallestRangeI(int[] nums, int k) { int minNum = Integer.MAX_VALUE; int maxNum = Integer.MIN_VALUE;
for (int num : nums) {
minNum = Math.min(minNum, num);
maxNum = Math.max(maxNum, num);
}
// Calculate the new maximum and minimum values after adding/subtracting k
int newMin = minNum + k;
int newMax = maxNum - k;
// The smallest possible range, ensuring it's not negative
return Math.max(0, newMax - newMin);
}
public static void main(String[] args) {
SmallestRangeI solution = new SmallestRangeI();
int[] nums = {1, 3, 6};
int k =
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?