Created
September 30, 2018 02:30
-
-
Save phanngoc/d3dec6532adffd22389f89ab4d491731 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"fmt" | |
) | |
// MinMax comment | |
func MinMax(A []int) (int, int) { | |
min := A[0] | |
max := A[0] | |
for _, e := range A { | |
if e < min { | |
min = e | |
} | |
if e > max { | |
max = e | |
} | |
} | |
return min, max | |
} | |
func smallestRangeI(A []int, K int) int { | |
min, max := MinMax(A) | |
temBe, temHi, distant := 0, 0, max-min | |
for i := 1; i <= K; i++ { | |
temBe = min + i | |
temHi = max - i | |
temDis := temHi - temBe | |
if temDis >= 0 && temDis < distant { | |
distant = temDis | |
} | |
if (i + 1) <= K { | |
temBe = min + i | |
temHi = max - i - 1 | |
temDis = temHi - temBe | |
if temDis >= 0 && temDis < distant { | |
distant = temDis | |
} | |
} | |
temBe = min + i - 1 | |
temHi = max - i | |
temDis = temHi - temBe | |
if temDis >= 0 && temDis < distant { | |
distant = temDis | |
} | |
} | |
return distant | |
} | |
func main() { | |
a := []int{7, 8, 8} | |
k := 5 | |
res := smallestRangeI(a, k) | |
fmt.Println("res:", res) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment