- Translate each rule into one explicit state update.
- Maintain the invariant after every processed item.
- Return the accumulated state once all relevant input has been handled.
Code notes
- 50 lines of C++ from the credited upstream file 3102.cpp.
- The implementation visibly relies on sequence storage.
- 1 loop block detected.
Complexity
Count the number and nesting of passes over the input, then include the maintained containers in the memory estimate.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
1class Solution {2 public:3 int minimumDistance(vector<vector<int>>& points) {4 const auto [i, j] = maxManhattanDistance(points, -1);5 const auto [xi, yi] = maxManhattanDistance(points, i);6 const auto [xj, yj] = maxManhattanDistance(points, j);7 return min(manhattan(points, xi, yi), manhattan(points, xj, yj));8 }9 10 private:11 12 13 pair<int, int> maxManhattanDistance(const vector<vector<int>>& points,14 int excludedIndex) {15 int minSum = INT_MAX;16 int maxSum = INT_MIN;17 int minDiff = INT_MAX;18 int maxDiff = INT_MIN;19 int minSumIndex = -1;20 int maxSumIndex = -1;21 int minDiffIndex = -1;22 int maxDiffIndex = -1;23 24 for (int i = 0; i < points.size(); ++i) {25 if (i == excludedIndex)26 continue;27 const int x = points[i][0];28 const int y = points[i][1];29 const int sum = x + y;30 const int diff = x - y;31 if (sum < minSum)32 minSum = sum, minSumIndex = i;33 if (sum > maxSum)34 maxSum = sum, maxSumIndex = i;35 if (diff < minDiff)36 minDiff = diff, minDiffIndex = i;37 if (diff > maxDiff)38 maxDiff = diff, maxDiffIndex = i;39 }40 41 return maxSum - minSum >= maxDiff - minDiff42 ? pair<int, int>(minSumIndex, maxSumIndex)43 : pair<int, int>(minDiffIndex, maxDiffIndex);44 }45 46 int manhattan(const vector<vector<int>>& points, int i, int j) {47 return abs(points[i][0] - points[j][0]) + abs(points[i][1] - points[j][1]);48 }49};50