2
public int smallestRangeII(int[] nums, int k) {4
if (n == 1) return 0; // Max and min are the same8
// score = minimum(max-min)9
// To minimize the score, need to add k to small numbers (Initial part of array)10
// and need to subtract k from large numbers (End part of array)12
// It might happen that when we add k to a number13
// And subtract k from another number14
// The minimum and maximum can change16
// If k>=nums[n-1]-nums[0] the score will always increase if we add k to some17
// numbers and subtract k from some numbers18
// Hence, the minimum score is the current score20
if (k >= nums[n - 1] - nums[0]) {21
return nums[n - 1] - nums[0];24
// Now k < nums[n-1]-nums[0]25
// Add k to first p numbers and subtract k from remaining numbers26
// LEFT SEGMENT: First p numbers where we add k27
// RIGHT SEGMENT: Remaining numbers where we subtract k29
// LEFT SEGMENT: (nums[0]+k,nums[1]+k,......,nums[p-1]+k)30
// RIGHT SEGMENT: (nums[p]-k,nums[p+1]-k,.......nums[n-1]-k)32
// Question: Where is p?33
// Answer: We try all possible values for p and min score everytime35
// After subtracting and adding k to numbers,36
// the new minimum and maximum will be37
// minimum = min (nums[0]+k , nums[p]-k)38
// maximum = max (nums[p-1]+k, nums[n-1]-k)40
int minScore = nums[n - 1] - nums[0];41
for (int p = 1; p < n; p++) {42
int min = Math.min(nums[0] + k, nums[p] - k);43
int max = Math.max(nums[p - 1] + k, nums[n - 1] - k);44
minScore = Math.min(minScore, max - min);