Skip to content

Commit 65d2fd6

Browse files
Alexander ChernikovAlexander Chernikov
authored andcommitted
add 0910 smallest-range-ii
1 parent e3fd0d2 commit 65d2fd6

File tree

3 files changed

+112
-0
lines changed

3 files changed

+112
-0
lines changed
Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
package leetcode
2+
3+
import "sort"
4+
5+
func SmallestRangeII(A []int, K int) int {
6+
n := len(A)
7+
sort.Ints(A)
8+
var ans int = A[n-1] - A[0]
9+
for i := 0; i < n-1; i++ {
10+
a, b := A[i], A[i+1]
11+
high := max(A[n-1]-K, a+K)
12+
low := min(A[0]+K, b-K)
13+
ans = min(ans, high-low)
14+
}
15+
16+
return ans
17+
}
18+
19+
func max(a, b int) int {
20+
if a > b {
21+
return a
22+
}
23+
return b
24+
}
25+
26+
func min(a, b int) int {
27+
if a < b {
28+
return a
29+
}
30+
return b
31+
}
Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
package leetcode
2+
3+
import (
4+
"fmt"
5+
"testing"
6+
)
7+
8+
type question910 struct {
9+
para910
10+
ans910
11+
}
12+
13+
type para910 struct {
14+
A []int
15+
K int
16+
}
17+
18+
type ans910 struct {
19+
one int
20+
}
21+
22+
func Test_Problem910(t *testing.T) {
23+
24+
qs := []question910{
25+
26+
{
27+
para910{[]int{1}, 0},
28+
ans910{0},
29+
},
30+
{
31+
para910{[]int{0, 10}, 2},
32+
ans910{6},
33+
},
34+
{
35+
para910{[]int{1, 3, 6}, 3},
36+
ans910{3},
37+
},
38+
}
39+
40+
fmt.Printf("------------------------Leetcode Problem 910------------------------\n")
41+
42+
for _, q := range qs {
43+
_, p := q.ans910, q.para910
44+
fmt.Printf("【input】:%v 【output】:%v\n", p, SmallestRangeII(p.A, p.K))
45+
}
46+
fmt.Printf("\n\n\n")
47+
}
Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
Given an array A of integers, for each integer A[i] we need to choose either x = -K or x = K, and add x to A[i] (only once).
2+
3+
After this process, we have some array B.
4+
5+
Return the smallest possible difference between the maximum value of B and the minimum value of B.
6+
7+
8+
9+
Example 1:
10+
```
11+
Input: A = [1], K = 0
12+
Output: 0
13+
Explanation: B = [1]
14+
```
15+
Example 2:
16+
```
17+
Input: A = [0,10], K = 2
18+
Output: 6
19+
Explanation: B = [2,8]
20+
```
21+
Example 3:
22+
```
23+
Input: A = [1,3,6], K = 3
24+
Output: 3
25+
Explanation: B = [4,6,3]
26+
```
27+
28+
29+
Note:
30+
31+
1 <= A.length <= 10000
32+
0 <= A[i] <= 10000
33+
0 <= K <= 10000
34+

0 commit comments

Comments
 (0)