
Sponsored
Sponsored
After sorting the array, our potential strategy is to focus on bridging the maximum and minimum gap by controlling possible breakpoints where the boundary conditions for minimum and maximum flip due to the presorted state.
Time Complexity: O(n log n) due to the sorting operation. Space Complexity: O(1) if we ignore input space.
1def smallestRangeII(nums, k):
2 nums.sort()
3 result = nums[-1] - nums[0]
4 for i in range(len(nums) - 1):
5 high = max(nums[i] + k, nums[-1] - k)
6 low = min(nums[0] + k, nums[i + 1] - k)
7 result = min(result, high - low)
8 return result
9
10nums = [1, 3, 6]
11k = 3
12print(smallestRangeII(nums, k)) # Output: 3This Python code focuses on calculating different potential optimal ranges by adjusting endpoints dynamically around sorted points with ±k considerations.
A slight variation that considers minimizing and maximizing simultaneously, with the goal of finding directly altered extremes without sequence traversals.
Time Complexity: O(n log n), Space Complexity: O(1) for array due to in-place.
1using System;
2
public class SmallestRangeII {
public int SmallestRange(int[] nums, int k) {
Array.Sort(nums);
int minVal = nums[0] + k;
int maxVal = nums[nums.Length - 1] - k;
int result = nums[nums.Length - 1] - nums[0];
for (int i = 0; i < nums.Length - 1; i++) {
int currentMax = Math.Max(nums[i] + k, maxVal);
int currentMin = Math.Min(minVal, nums[i + 1] - k);
result = Math.Min(result, currentMax - currentMin);
}
return result;
}
public static void Main(string[] args) {
SmallestRangeII solution = new SmallestRangeII();
int[] nums = {1, 3, 6};
int k = 3;
Console.WriteLine(solution.SmallestRange(nums, k));
}
}For C#, possibilities are identified and recalculated succinctly based on splaying between conceivable limits, testing reduction consecutively.