go: add «624. Maximum Distance in Arrays»

Signed-off-by: Matej Focko <me@mfocko.xyz>
This commit is contained in:
Matej Focko 2024-08-16 11:19:25 +02:00
parent a347dcfcd6
commit 83202647ef
Signed by: mfocko
SSH key fingerprint: SHA256:icm0fIOSJUpy5+1x23sfr+hLtF9UhY8VpMC7H4WFJP8

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