mirror of
https://gitlab.com/mfocko/LeetCode.git
synced 2024-11-09 15:59:06 +01:00
go: add «624. Maximum Distance in Arrays»
Signed-off-by: Matej Focko <me@mfocko.xyz>
This commit is contained in:
parent
a347dcfcd6
commit
83202647ef
1 changed files with 40 additions and 0 deletions
40
go/maximum-distance-in-arrays.go
Normal file
40
go/maximum-distance-in-arrays.go
Normal file
|
@ -0,0 +1,40 @@
|
||||||
|
package main
|
||||||
|
|
||||||
|
type Range struct {
|
||||||
|
min, max int
|
||||||
|
}
|
||||||
|
|
||||||
|
func RangeFromArray(array []int) Range {
|
||||||
|
return Range{
|
||||||
|
min: array[0],
|
||||||
|
max: array[len(array)-1],
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *Range) Update(subarray []int) {
|
||||||
|
r.min = min(r.min, subarray[0])
|
||||||
|
r.max = max(r.max, subarray[len(subarray)-1])
|
||||||
|
}
|
||||||
|
|
||||||
|
func abs(x int) int {
|
||||||
|
return max(-x, x)
|
||||||
|
}
|
||||||
|
|
||||||
|
func RangeMaxDistance(x, y Range) int {
|
||||||
|
return max(
|
||||||
|
abs(x.min-y.max),
|
||||||
|
abs(y.min-x.max),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
func maxDistance(arrays [][]int) int {
|
||||||
|
foundDistance := 0
|
||||||
|
|
||||||
|
extremes := RangeFromArray(arrays[0])
|
||||||
|
for i := 1; i < len(arrays); i++ {
|
||||||
|
foundDistance = max(foundDistance, RangeMaxDistance(extremes, RangeFromArray(arrays[i])))
|
||||||
|
extremes.Update(arrays[i])
|
||||||
|
}
|
||||||
|
|
||||||
|
return foundDistance
|
||||||
|
}
|
Loading…
Reference in a new issue