Skip to content

Commit 2fef78b

Browse files
author
openset
committed
Add: Smallest Range I
1 parent 4b36bc2 commit 2fef78b

File tree

2 files changed

+55
-0
lines changed

2 files changed

+55
-0
lines changed
Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1 +1,17 @@
11
package smallest_range_i
2+
3+
func smallestRangeI(A []int, K int) int {
4+
min, max := A[0], A[0]
5+
for _, v := range A {
6+
if v < min {
7+
min = v
8+
} else if v > max {
9+
max = v
10+
}
11+
}
12+
ans := max - min - 2*K
13+
if ans < 0 {
14+
return 0
15+
}
16+
return ans
17+
}
Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1 +1,40 @@
11
package smallest_range_i
2+
3+
import "testing"
4+
5+
type caseType struct {
6+
input []int
7+
k int
8+
expected int
9+
}
10+
11+
func TestSmallestRangeI(t *testing.T) {
12+
tests := [...]caseType{
13+
{
14+
input: []int{1},
15+
k: 0,
16+
expected: 0,
17+
},
18+
{
19+
input: []int{0, 10},
20+
k: 2,
21+
expected: 6,
22+
},
23+
{
24+
input: []int{1, 3, 6},
25+
k: 3,
26+
expected: 0,
27+
},
28+
{
29+
input: []int{1, 3, 5, 7, 9},
30+
k: 1,
31+
expected: 6,
32+
},
33+
}
34+
for _, tc := range tests {
35+
output := smallestRangeI(tc.input, tc.k)
36+
if output != tc.expected {
37+
t.Fatalf("input: %v, output: %v, expected: %v", tc.input, output, tc.expected)
38+
}
39+
}
40+
}

0 commit comments

Comments
 (0)