File tree Expand file tree Collapse file tree 1 file changed +47
-0
lines changed
December_LeetCode_Challenge Expand file tree Collapse file tree 1 file changed +47
-0
lines changed Original file line number Diff line number Diff line change 1+ Given an array A of integers , for each integer A [i ] we need to choose
2+ either x = - K or x = K , and add x to A [i ] (only once ).
3+
4+ After this process , we have some array B .
5+
6+ Return the smallest possible difference between the maximum value of B
7+ and the minimum value of B .
8+
9+
10+ Example 1 :
11+ Input : A = [1 ], K = 0
12+ Output : 0
13+ Explanation : B = [1 ]
14+
15+ Example 2 :
16+ Input : A = [0 ,10 ], K = 2
17+ Output : 6
18+ Explanation : B = [2 ,8 ]
19+
20+ Example 3 :
21+ Input : A = [1 ,3 ,6 ], K = 3
22+ Output : 3
23+ Explanation : B = [4 ,6 ,3 ]
24+
25+
26+ Note :
27+ 1 <= A .length <= 10000
28+ 0 <= A [i ] <= 10000
29+ 0 <= K <= 10000
30+
31+
32+ # O(nlogn) Time and O(1) Space
33+ class Solution :
34+ def smallestRangeII (self , A : List [int ], K : int ) -> int :
35+
36+ A .sort ()
37+
38+ result = A [- 1 ] - A [0 ]
39+
40+ for i in range (len (A )- 1 ):
41+
42+ max_val = max (A [i ] + K , A [- 1 ] - K )
43+ min_val = min (A [0 ] + K , A [i + 1 ] - K )
44+
45+ result = min (result , max_val - min_val )
46+
47+ return result
You can’t perform that action at this time.
0 commit comments