Sort the array. For each possible partition, increase all elements to the left by k and decrease all elements to the right by k. The answer is the minimum difference between the new max and min over all partitions.
classSolution {
public:int smallestRangeII(vector<int>& nums, int k) {
sort(nums.begin(), nums.end());
int n = nums.size(), ans = nums[n-1] - nums[0];
for (int i =0; i < n-1; ++i) {
int hi = max(nums[i]+k, nums[n-1]-k);
int lo = min(nums[0]+k, nums[i+1]-k);
ans = min(ans, hi-lo);
}
return ans;
}
};
1
2
3
4
5
6
7
8
9
10
11
12
13
funcsmallestRangeII(nums []int, kint) int {
sort.Ints(nums)
n:= len(nums)
ans:=nums[n-1] -nums[0]
fori:=0; i < n-1; i++ {
hi:= max(nums[i]+k, nums[n-1]-k)
lo:= min(nums[0]+k, nums[i+1]-k)
ifhi-lo < ans { ans = hi-lo }
}
returnans}
func max(a, bint) int { ifa > b { returna }; returnb }
func min(a, bint) int { ifa < b { returna }; returnb }
1
2
3
4
5
6
7
8
9
10
11
12
classSolution {
publicintsmallestRangeII(int[] nums, int k) {
Arrays.sort(nums);
int n = nums.length, ans = nums[n-1]- nums[0];
for (int i = 0; i < n-1; ++i) {
int hi = Math.max(nums[i]+k, nums[n-1]-k);
int lo = Math.min(nums[0]+k, nums[i+1]-k);
ans = Math.min(ans, hi-lo);
}
return ans;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
classSolution {
funsmallestRangeII(nums: IntArray, k: Int): Int {
nums.sort()
var ans = nums.last() - nums.first()
for (i in0 until nums.size-1) {
val hi = maxOf(nums[i]+k, nums.last()-k)
val lo = minOf(nums.first()+k, nums[i+1]-k)
ans = minOf(ans, hi-lo)
}
return ans
}
}
1
2
3
4
5
6
7
8
9
classSolution:
defsmallestRangeII(self, nums: list[int], k: int) -> int:
nums.sort()
ans = nums[-1] - nums[0]
for i in range(len(nums)-1):
hi = max(nums[i]+k, nums[-1]-k)
lo = min(nums[0]+k, nums[i+1]-k)
ans = min(ans, hi-lo)
return ans
1
2
3
4
5
6
7
8
9
10
11
12
13
impl Solution {
pubfnsmallest_range_ii(mut nums: Vec<i32>, k: i32) -> i32 {
nums.sort();
let n = nums.len();
letmut ans = nums[n-1] - nums[0];
for i in0..n-1 {
let hi = nums[i]+k.max(nums[n-1]-k);
let lo = nums[0]+k.min(nums[i+1]-k);
ans = ans.min(hi-lo);
}
ans
}
}