Skip to content

Commit 1dff0c7

Browse files
author
Shuo
authored
Merge pull request #384 from openset/develop
Add: Smallest Range I
2 parents 79945f2 + e1c5160 commit 1dff0c7

File tree

2 files changed

+60
-0
lines changed

2 files changed

+60
-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: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1 +1,45 @@
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+
input: []int{18, 16, 12, 7, 9, 3, 5},
35+
k: 6,
36+
expected: 3,
37+
},
38+
}
39+
for _, tc := range tests {
40+
output := smallestRangeI(tc.input, tc.k)
41+
if output != tc.expected {
42+
t.Fatalf("input: %v, output: %v, expected: %v", tc.input, output, tc.expected)
43+
}
44+
}
45+
}

0 commit comments

Comments
 (0)