Skip to content

Commit 1ee2fdd

Browse files
committed
Runtime: 39 ms (Top 5.74%) | Memory: 50.2 MB (Top 6.63%)
1 parent 68be080 commit 1ee2fdd

File tree

1 file changed

+15
-14
lines changed

1 file changed

+15
-14
lines changed
Original file line numberDiff line numberDiff line change
@@ -1,50 +1,51 @@
1+
// Runtime: 39 ms (Top 5.74%) | Memory: 50.2 MB (Top 6.63%)
12
class Solution {
23
public int smallestRangeII(int[] nums, int k) {
34
int n = nums.length;
45
if (n==1)
56
return 0; // Max and min are the same
6-
7+
78
Arrays.sort(nums);
8-
9+
910
// score = minimum(max-min)
1011
// To minimize the score, need to add k to small numbers (Initial part of array)
1112
// and need to subtract k from large numbers (End part of array)
12-
13+
1314
// It might happen that when we add k to a number
1415
// And subtract k from another number
15-
// The minimum and maximum can change
16-
16+
// The minimum and maximum can change
17+
1718
// If k>=nums[n-1]-nums[0] the score will always increase if we add k to some
1819
// numbers and subtract k from some numbers
1920
// Hence, the minimum score is the current score
20-
21+
2122
if (k >= nums[n-1]-nums[0]) {
2223
return nums[n-1]-nums[0];
2324
}
24-
25+
2526
// Now k < nums[n-1]-nums[0]
2627
// Add k to first p numbers and subtract k from remaining numbers
2728
// LEFT SEGMENT: First p numbers where we add k
2829
// RIGHT SEGMENT: Remaining numbers where we subtract k
29-
30+
3031
// LEFT SEGMENT: (nums[0]+k,nums[1]+k,......,nums[p-1]+k)
3132
// RIGHT SEGMENT: (nums[p]-k,nums[p+1]-k,.......nums[n-1]-k)
32-
33+
3334
// Question: Where is p?
3435
// Answer: We try all possible values for p and min score everytime
35-
36-
// After subtracting and adding k to numbers,
36+
37+
// After subtracting and adding k to numbers,
3738
// the new minimum and maximum will be
3839
// minimum = min (nums[0]+k , nums[p]-k)
3940
// maximum = max (nums[p-1]+k, nums[n-1]-k)
40-
41+
4142
int minScore = nums[n-1]-nums[0];
4243
for (int p=1;p<n;p++) {
4344
int min = Math.min(nums[0]+k,nums[p]-k);
4445
int max = Math.max(nums[p-1]+k,nums[n-1]-k);
4546
minScore = Math.min(minScore,max-min);
4647
}
47-
48+
4849
return minScore;
4950
}
50-
}
51+
}

0 commit comments

Comments
 (0)