
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.
1function smallestRangeII(nums, k) {
2 nums.sort((a, b) => a - b);
3 let result = nums[nums.length - 1] - nums[0];
4 for (let i = 0; i < nums.length - 1; i++) {
5 let high = Math.max(nums[i] + k, nums[nums.length - 1] - k);
6 let low = Math.min(nums[0] + k, nums[i + 1] - k);
7 result = Math.min(result, high - low);
8 }
9 return result;
10}
11
12const nums = [1, 3, 6];
13const k = 3;
14console.log(smallestRangeII(nums, k)); // Output: 3This JavaScript function calculates the minimal score by evaluating each possible breakpoint between sorted array elements and dynamically updating the range.
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.
1#include <iostream>
2#include <vector>
#include <algorithm>
using namespace std;
int smallestRangeII(vector<int>& nums, int k) {
sort(nums.begin(), nums.end());
int minVal = nums[0] + k, maxVal = nums.back() - k;
int result = nums.back() - nums[0];
for (int i = 0; i < nums.size() - 1; ++i) {
int currentMax = max(nums[i] + k, maxVal);
int currentMin = min(minVal, nums[i + 1] - k);
result = min(result, currentMax - currentMin);
}
return result;
}
int main() {
vector<int> nums = {1, 3, 6};
int k = 3;
cout << "Result: " << smallestRangeII(nums, k) << endl;
return 0;
}In C++, a direct calculation using sorted arrays where min/max hypothetical calculations are executed compactly around putative extremes and adjusted iteratively.