add 0910 smallest-range-ii

This commit is contained in:
Alexander Chernikov
2020-12-21 13:58:49 +03:00
parent e3fd0d2671
commit 65d2fd668b
3 changed files with 112 additions and 0 deletions

View File

@ -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
}

View File

@ -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")
}

View File

@ -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