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
}