The trick here is to name the state correctly, then let the implementation follow. For 1266. Minimum Time Visiting All Points, the solution in this repository is mainly a straightforward implementation solution.
Guide
What?
We want to turn the problem statement into a smaller set of decisions the computer can repeat safely. Instead of trying to be clever immediately, read the code as a sequence of questions:
- What state are we keeping?
- How do we move from one state to the next?
- When do we know the answer is already determined?
For this file, the main tools are: straightforward implementation.
Guide
When?
This is the kind of solution you want when the problem has structure hiding inside a messy-looking input. The accepted code reduces that pressure by storing exactly the information that remains useful later.
The important function names to track are minTimeToVisitAllPoints.
Guide
Why?
The solution works because it narrows the problem until every update has a clear reason to exist.
- The two-dimensional vector is the memory of the solution: grid state, DP state, or adjacency shape.
- The final return is not magic; it is the invariant after the loops or recursion have finished doing their accounting.
Guide
How?
Walk through the solution in this order:
- Read the setup variables first.
- Follow the main loop or recursive helper next.
- Watch where invalid states get skipped.
- Check which value survives to the return statement.
The most important competitive-programming habit here is to trust the invariant. Once the invariant is right, the loops become much less scary.
Guide
Complexity
- Time: O(n) to O(n log n), depending on the dominant loop or data structure operation
- Space: O(n) in the usual case for auxiliary containers or recursion
Guide
C++ Solution
Your submission
The accepted solution
01//Runtime: 4 ms, faster than 99.42% of C++ online submissions for Minimum Time Visiting All Points.
02//Memory Usage: 10.1 MB, less than 100.00% of C++ online submissions for Minimum Time Visiting All Points.
03
04class Solution {
05public:
06 int minTimeToVisitAllPoints(vector<vector<int>>& points) {
07 if(points.size() < 2) return 0;
08 int steps = 0;
09 int xdiff, ydiff, diagSteps, straightSteps;
10 for(int i = 1; i < points.size(); i++){
11 xdiff = points[i][0] - points[i-1][0];
12 ydiff = points[i][1] - points[i-1][1];
13 //Method 1
14 // diagSteps = min(abs(xdiff), abs(ydiff));
15 // straightSteps = max(abs(xdiff), abs(ydiff)) - diagSteps;
16 // steps += (diagSteps + straightSteps);
17 //Method 2, optimized from Method 1
18 steps += max(abs(xdiff), abs(ydiff));
19 }
20 return steps;
21 }
22};
Cost