Leetcode - Create Target Array in the Given Order
Leetcode - Array Transformation

Leetcode - Minimum Time Visiting All Points

violet posted @ Apr 02, 2020 05:29:07 AM in 算法 with tags Algorithm Golang array , 188 阅读

https://leetcode.com/problems/minimum-time-visiting-all-points/

On a plane there are n points with integer coordinates points[i] = [xi, yi]. Your task is to find the minimum time in seconds to visit all points.

You can move according to the next rules:

  • In one second always you can either move vertically, horizontally by one unit or diagonally (it means to move one unit vertically and one unit horizontally in one second).
  • You have to visit the points in the same order as they appear in the array.

 

func minTimeToVisitAllPoints(points [][]int) int {
    result := 0
    for i := 1; i < len(points); i++ {
        cur := points[i]
        prev := points[i-1]
        result += max(abs(cur[0] - prev[0]), abs(cur[1] - prev[1]))
    }
    return result
}

func max(a, b int) int {
    if a > b {
        return a
    }
    return b
}

func abs(a int) int {
    if a < 0 {
        return 0 - a
    }
    return a
}

登录 *


loading captcha image...
(输入验证码)
or Ctrl+Enter