1
+ // Runtime: 39 ms (Top 5.74%) | Memory: 50.2 MB (Top 6.63%)
1
2
class Solution {
2
3
public int smallestRangeII (int [] nums , int k ) {
3
4
int n = nums .length ;
4
5
if (n ==1 )
5
6
return 0 ; // Max and min are the same
6
-
7
+
7
8
Arrays .sort (nums );
8
-
9
+
9
10
// score = minimum(max-min)
10
11
// To minimize the score, need to add k to small numbers (Initial part of array)
11
12
// and need to subtract k from large numbers (End part of array)
12
-
13
+
13
14
// It might happen that when we add k to a number
14
15
// And subtract k from another number
15
- // The minimum and maximum can change
16
-
16
+ // The minimum and maximum can change
17
+
17
18
// If k>=nums[n-1]-nums[0] the score will always increase if we add k to some
18
19
// numbers and subtract k from some numbers
19
20
// Hence, the minimum score is the current score
20
-
21
+
21
22
if (k >= nums [n -1 ]-nums [0 ]) {
22
23
return nums [n -1 ]-nums [0 ];
23
24
}
24
-
25
+
25
26
// Now k < nums[n-1]-nums[0]
26
27
// Add k to first p numbers and subtract k from remaining numbers
27
28
// LEFT SEGMENT: First p numbers where we add k
28
29
// RIGHT SEGMENT: Remaining numbers where we subtract k
29
-
30
+
30
31
// LEFT SEGMENT: (nums[0]+k,nums[1]+k,......,nums[p-1]+k)
31
32
// RIGHT SEGMENT: (nums[p]-k,nums[p+1]-k,.......nums[n-1]-k)
32
-
33
+
33
34
// Question: Where is p?
34
35
// 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,
37
38
// the new minimum and maximum will be
38
39
// minimum = min (nums[0]+k , nums[p]-k)
39
40
// maximum = max (nums[p-1]+k, nums[n-1]-k)
40
-
41
+
41
42
int minScore = nums [n -1 ]-nums [0 ];
42
43
for (int p =1 ;p <n ;p ++) {
43
44
int min = Math .min (nums [0 ]+k ,nums [p ]-k );
44
45
int max = Math .max (nums [p -1 ]+k ,nums [n -1 ]-k );
45
46
minScore = Math .min (minScore ,max -min );
46
47
}
47
-
48
+
48
49
return minScore ;
49
50
}
50
- }
51
+ }
0 commit comments