LeetCode/go/maximum-distance-in-arrays.go
Matej Focko 83202647ef
go: add «624. Maximum Distance in Arrays»
Signed-off-by: Matej Focko <me@mfocko.xyz>
2024-08-16 11:19:25 +02:00

40 lines
709 B
Go

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
}