Between two points, diagonal moves cover both axes together, leaving the larger coordinate difference as the exact travel time. Sum that Chebyshev distance.
Complexity
O(n) time and O(1) space.
Find the minimum seconds required to visit ordered points while moving horizontally, vertically, or diagonally.
Between two points, diagonal moves cover both axes together, leaving the larger coordinate difference as the exact travel time. Sum that Chebyshev distance.
O(n) time and O(1) space.
package main
func minTimeToVisitAllPoints(points [][]int) int {
time := 0
for index := 1; index < len(points); index++ {
dx := points[index][0] - points[index-1][0]
if dx < 0 {
dx = -dx
}
dy := points[index][1] - points[index-1][1]
if dy < 0 {
dy = -dy
}
if dx > dy {
time += dx
} else {
time += dy
}
}
return time
}
class Solution:
def minTimeToVisitAllPoints(self, points: list[list[int]]) -> int:
return sum(max(abs(x2 - x1), abs(y2 - y1)) for (x1, y1), (x2, y2) in zip(points, points[1:]))
function minTimeToVisitAllPoints(points: number[][]): number {
let time = 0; for (let index = 1; index < points.length; index += 1) time += Math.max(Math.abs(points[index][0] - points[index - 1][0]), Math.abs(points[index][1] - points[index - 1][1])); return time;
}