You are given an integer array nums
and an integer k
. For each element in the nums
array, you can increase or decrease it by k
at most once.
The objective is to minimize the difference between the maximum and minimum values of the array after performing at most one operation (+k or -k) on each element.
Return the smallest possible difference between the maximum and minimum values of the array after performing the mentioned operation.
nums
array distinct?
nums
and k
?
1 <= nums.length <= 10^4
0 <= k <= 10^4
0 <= nums[i] <= 10^4
k
be zero?
k
is zero, the difference will naturally be the difference between the maximum and minimum of the original array.k
will shift the possible range of values the elements can take.min(nums) - k
and the new maximum value can be max(nums) + k
.k
and increasing the lowest value by k
, the potential range of the array can be tightened around the original mean.min(nums)
max(nums)
min(nums) + k
max(nums) - k
max(0, (max(nums) - k) - (min(nums) + k))
Here’s the implementation of the above strategy in Python.
def smallestRangeI(nums, k):
min_num = min(nums)
max_num = max(nums)
return max(0, (max_num - k) - (min_num + k))
# Example usage:
nums = [1, 3, 6]
k = 3
print(smallestRangeI(nums, k)) # Output: 0
O(n)
, where n
is the number of elements in nums
.O(1)
.Thus, the overall time complexity of the solution is O(n)
.
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?