Leetcode 1266. Minimum Time Visiting All Points
You are given an array points
representing the coordinates of different points on a 2D plane, where points[i] = [xi, yi]
. The task is to find the minimum time required to visit all points in the order given by points
.
You can move from a point (x1, y1)
to another point (x2, y2)
in the following ways:
(x1, y1)
to (x1+1, y1+1)
or (x1-1, y1-1)
.(x1, y1)
to (x1+1, y1)
or (x1-1, y1)
.(x1, y1)
to (x1, y1+1)
or (x1, y1-1)
.The time to move from (x1, y1)
to (x2, y2)
is the maximum of the absolute differences in their coordinates: max(abs(x2 - x1), abs(y2 - y1))
.
Write a function minTimeToVisitAllPoints
that returns the minimum time required to visit all the given points in order.
Given points:
[[1,1],[3,4],[-1,0]]
Output: 7
max(abs(x2 - x1), abs(y2 - y1))
, where (x1, y1)
is the current point and (x2, y2)
is the next point.The time complexity for this solution is O(N) where N is the number of points. This is because we are simply iterating through the list of points once.
Here is the implementation in C++:
#include <vector>
#include <cmath>
class Solution {
public:
int minTimeToVisitAllPoints(std::vector<std::vector<int>>& points) {
int total_time = 0;
for (size_t i = 1; i < points.size(); ++i) {
int x1 = points[i-1][0], y1 = points[i-1][1];
int x2 = points[i][0], y2 = points[i][1];
total_time += std::max(std::abs(x2 - x1), std::abs(y2 - y1));
}
return total_time;
}
};
This code will correctly compute the minimum time required to visit all points in the given order by adhering to the movements defined in the problem statement.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?