1266. Minimum Time Visiting All Points (LeetCode) (solution: C++, C#)


Problem Name: 1266. Minimum Time Visiting All Points
Problem Link: https://leetcode.com/problems/minimum-time-visiting-all-points/
Difficulty: Easy
Tag: Array | Math | Geometry
Language: C# | C++
OJ: LeetCode

Algorithm:
Initialize Variables:
sum: Initialize a variable to store the total time.
currentX, currentY: Initialize variables to store the current position, initially set to the coordinates of the first point (points[0]).
Iterate Through Points:
💣Start a loop from i = 1 since you've already set the initial position.
💣 For each point in the array (points), calculate the absolute differences between the current position (currentX, currentY) and the coordinates of the current point (points[i]).
💣Calculate x as the absolute difference between the x-coordinates (Math.Abs(currentX - points[i][0])).
💣Calculate y as the absolute difference between the y-coordinates (Math.Abs(currentY - points[i][1])).
Update Total Time:
Add the maximum of x and y to the sum. This represents the time taken to move from the current point to the next point.
Update Current Position:
Update currentX and currentY with the coordinates of the current point (points[i]).
Return Total Time:
After the loop is complete, return the total time (sum), which represents the minimum time to visit all points.

Code(C#)
public class Solution
{
    public int MinTimeToVisitAllPoints(int[][] points)
    {
        int sum = 0;
        int currentX = points[0][0], currentY = points[0][1];
        for(int i=1; i<points.Length; i++)
        {
            int x = Math.Abs(currentX - points[i][0]);
            int y = Math.Abs(currentY - points[i][1]);
            sum += Math.Max(x, y);
            currentX = points[i][0];
            currentY = points[i][1];
        }
        return sum;
    }
}

Code(C++)
class Solution {
public:
    int minTimeToVisitAllPoints(vector<vector<int>>& points) {
        int sum = 0;
        int currentX = points[0][0], currentY = points[0][1];
        
        for (int i = 1; i < points.size(); i++) {
            int x = abs(currentX - points[i][0]);
            int y = abs(currentY - points[i][1]);
            sum += max(x, y);
            currentX = points[i][0];
            currentY = points[i][1];
        }
        
        return sum;
    }
};