Leetcode 910. Smallest Range II
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.
nums = [1, 3, 6]
, k = 3
Output: 3
Explanation: Change nums
to be [4, 6, 3]
. The score is 6 - 3 = 3
.nums
take?
nums
are integers and can be positive, negative or zero.nums
?
nums
will be between 1
and 10^4
.k
is zero?
k
can be zero in which case we won’t change any elements, but we need to handle that explicitly.To minimize the difference between the max and min values of the transformed array:
nums[n-1] - nums[0]
(max - min of the sorted array).k
:
k
to the minimum element or subtract k
from it,k
from the maximum element or add k
to it,nums[n-1] - nums[0]
.+k
or -k
to the boundaries:
i
from 0
to n-2
:
nums[i] + k
and nums[n-1] - k
.nums[0] + k
and nums[i+1] - k
.public class SmallestRangeII {
public int smallestRangeII(int[] nums, int k) {
// Sort the array
Arrays.sort(nums);
int n = nums.length;
// Initial max and min range as it is before any modifications
int result = nums[n - 1] - nums[0];
// Iterate through the array and calculate the potential new minimum and maximum ranges
for (int i = 0; i < n - 1; i++) {
int maxVal = Math.max(nums[i] + k, nums[n - 1] - k);
int minVal = Math.min(nums[0] + k, nums[i + 1] - k);
// Update the result with the minimum range
result = Math.min(result, maxVal - minVal);
}
return result;
}
}
O(n log n)
time.O(n)
time.
Thus, the overall time complexity is O(n log n)
.This strategy ensures we explore all possible transformations effectively to find the minimum possible score.
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?