- Choose the invariant that makes a window valid or useful.
- Advance the right boundary and add the new element.
- Move the left boundary only as needed while maintaining the invariant and updating the answer.
Code notes
- 89 lines of C++ from the credited upstream file 3464.cpp.
- The implementation visibly relies on sequence storage, work queue.
- 4 loop blocks detected.
Complexity
Confirm that neither pointer moves backwards; if so, the scan is usually linear apart from the window’s data-structure operations.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
1struct Sequence {2 int startX;3 int startY;4 int endX;5 int endY;6 int length;7};8 9class Solution {10 public:11 int maxDistance(int side, vector<vector<int>>& points, int k) {12 const vector<pair<int, int>> ordered = getOrderedPoints(side, points);13 int l = 0;14 int r = side;15 16 while (l < r) {17 const int m = (l + r + 1) / 2;18 if (isValidDistance(ordered, k, m))19 l = m;20 else21 r = m - 1;22 }23 24 return l;25 }26 27 private:28 29 30 bool isValidDistance(const vector<pair<int, int>>& ordered, int k, int d) {31 deque<Sequence> dq{{ordered[0].first, ordered[0].second, ordered[0].first,32 ordered[0].second, 1}};33 int maxLength = 1;34 35 for (int i = 1; i < ordered.size(); ++i) {36 const auto& [x, y] = ordered[i];37 int startX = x;38 int startY = y;39 int length = 1;40 while (!dq.empty() &&41 (abs(x - dq.front().endX) + abs(y - dq.front().endY) >= d)) {42 if (abs(x - dq.front().startX) + abs(y - dq.front().startY) >= d &&43 dq.front().length + 1 >= length) {44 startX = dq.front().startX;45 startY = dq.front().startY;46 length = dq.front().length + 1;47 maxLength = max(maxLength, length);48 }49 dq.pop_front();50 }51 dq.emplace_back(startX, startY, x, y, length);52 }53 54 return maxLength >= k;55 }56 57 58 59 vector<pair<int, int>> getOrderedPoints(int side,60 vector<vector<int>>& points) {61 vector<pair<int, int>> left;62 vector<pair<int, int>> top;63 vector<pair<int, int>> right;64 vector<pair<int, int>> bottom;65 66 for (const vector<int>& point : points) {67 const int x = point[0];68 const int y = point[1];69 if (x == 0 && y > 0)70 left.emplace_back(x, y);71 else if (x > 0 && y == side)72 top.emplace_back(x, y);73 else if (x == side && y < side)74 right.emplace_back(x, y);75 else76 bottom.emplace_back(x, y);77 }78 79 ranges::sort(left);80 ranges::sort(top);81 ranges::sort(right, greater<>());82 ranges::sort(bottom, greater<>());83 left.insert(left.end(), top.begin(), top.end());84 left.insert(left.end(), right.begin(), right.end());85 left.insert(left.end(), bottom.begin(), bottom.end());86 return left;87 }88};89