|
| 1 | +# frozen_string_literal: true |
| 2 | + |
| 3 | +# 1266. Minimum Time Visiting All Points |
| 4 | +# Easy |
| 5 | +# https://leetcode.com/problems/minimum-time-visiting-all-points/ |
| 6 | + |
| 7 | +=begin |
| 8 | +On a 2D plane, there are n points with integer coordinates points[i] = [xi, yi]. Return the minimum time in seconds to visit all the points in the order given by points. |
| 9 | +You can move according to these rules: |
| 10 | +* In 1 second, you can either: |
| 11 | + * move vertically by one unit, |
| 12 | + * move horizontally by one unit, or |
| 13 | + * move diagonally sqrt(2) units (in other words, move one unit vertically then one unit horizontally in 1 second). |
| 14 | +* You have to visit the points in the same order as they appear in the array. |
| 15 | +* You are allowed to pass through points that appear later in the order, but these do not count as visits. |
| 16 | +
|
| 17 | +Example 1: |
| 18 | +Input: points = [[1,1],[3,4],[-1,0]] |
| 19 | +Output: 7 |
| 20 | +Explanation: One optimal path is [1,1] -> [2,2] -> [3,3] -> [3,4] -> [2,3] -> [1,2] -> [0,1] -> [-1,0] |
| 21 | +Time from [1,1] to [3,4] = 3 seconds |
| 22 | +Time from [3,4] to [-1,0] = 4 seconds |
| 23 | +Total time = 7 seconds |
| 24 | +
|
| 25 | +Example 2: |
| 26 | +Input: points = [[3,2],[-2,2]] |
| 27 | +Output: 5 |
| 28 | +
|
| 29 | +Constraints: |
| 30 | +points.length == n |
| 31 | +1 <= n <= 100 |
| 32 | +points[i].length == 2 |
| 33 | +-1000 <= points[i][0], points[i][1] <= 1000 |
| 34 | +=end |
| 35 | + |
| 36 | +# @param {Integer[][]} points |
| 37 | +# @return {Integer} |
| 38 | +def min_time_to_visit_all_points(points) |
| 39 | + result = 0 |
| 40 | + (0...points.length - 1).each do |i| |
| 41 | + result += [(points[i][0] - points[i + 1][0]).abs, (points[i][1] - points[i + 1][1]).abs].max |
| 42 | + end |
| 43 | + result |
| 44 | +end |
| 45 | + |
| 46 | +# **************** # |
| 47 | +# TEST # |
| 48 | +# **************** # |
| 49 | + |
| 50 | +require "test/unit" |
| 51 | +class Test_min_time_to_visit_all_points < Test::Unit::TestCase |
| 52 | + def test_ |
| 53 | + assert_equal 7, min_time_to_visit_all_points([[1, 1], [3, 4], [-1, 0]]) |
| 54 | + assert_equal 5, min_time_to_visit_all_points([[3, 2], [-2, 2]]) |
| 55 | + end |
| 56 | +end |
0 commit comments