diff --git a/leetcode/0910-Smallest-Range-II/910.Smallest Range II.go b/leetcode/0910-Smallest-Range-II/910.Smallest Range II.go new file mode 100644 index 00000000..1082b451 --- /dev/null +++ b/leetcode/0910-Smallest-Range-II/910.Smallest Range II.go @@ -0,0 +1,31 @@ +package leetcode + +import "sort" + +func SmallestRangeII(A []int, K int) int { + n := len(A) + sort.Ints(A) + var ans int = A[n-1] - A[0] + for i := 0; i < n-1; i++ { + a, b := A[i], A[i+1] + high := max(A[n-1]-K, a+K) + low := min(A[0]+K, b-K) + ans = min(ans, high-low) + } + + return ans +} + +func max(a, b int) int { + if a > b { + return a + } + return b +} + +func min(a, b int) int { + if a < b { + return a + } + return b +} diff --git a/leetcode/0910-Smallest-Range-II/910.Smallest Range II_test.go b/leetcode/0910-Smallest-Range-II/910.Smallest Range II_test.go new file mode 100644 index 00000000..420c8fba --- /dev/null +++ b/leetcode/0910-Smallest-Range-II/910.Smallest Range II_test.go @@ -0,0 +1,47 @@ +package leetcode + +import ( + "fmt" + "testing" +) + +type question910 struct { + para910 + ans910 +} + +type para910 struct { + A []int + K int +} + +type ans910 struct { + one int +} + +func Test_Problem910(t *testing.T) { + + qs := []question910{ + + { + para910{[]int{1}, 0}, + ans910{0}, + }, + { + para910{[]int{0, 10}, 2}, + ans910{6}, + }, + { + para910{[]int{1, 3, 6}, 3}, + ans910{3}, + }, + } + + fmt.Printf("------------------------Leetcode Problem 910------------------------\n") + + for _, q := range qs { + _, p := q.ans910, q.para910 + fmt.Printf("【input】:%v 【output】:%v\n", p, SmallestRangeII(p.A, p.K)) + } + fmt.Printf("\n\n\n") +} diff --git a/leetcode/0910-Smallest-Range-II/README.md b/leetcode/0910-Smallest-Range-II/README.md new file mode 100644 index 00000000..aaa0e90c --- /dev/null +++ b/leetcode/0910-Smallest-Range-II/README.md @@ -0,0 +1,34 @@ +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). + +After this process, we have some array B. + +Return the smallest possible difference between the maximum value of B and the minimum value of B. + + + +Example 1: +``` +Input: A = [1], K = 0 +Output: 0 +Explanation: B = [1] +``` +Example 2: +``` +Input: A = [0,10], K = 2 +Output: 6 +Explanation: B = [2,8] +``` +Example 3: +``` +Input: A = [1,3,6], K = 3 +Output: 3 +Explanation: B = [4,6,3] +``` + + +Note: + + 1 <= A.length <= 10000 + 0 <= A[i] <= 10000 + 0 <= K <= 10000 +