- Identify the ordered answer range or sorted search domain.
- Write a predicate whose truth changes only once.
- Move the appropriate boundary after each midpoint check and return the final feasible position.
Code notes
- 44 lines of C++ from the credited upstream file 3288.cpp.
- The implementation visibly relies on sequence storage.
- 2 loop blocks detected.
Complexity
Multiply the logarithmic number of midpoint checks by the cost of one predicate evaluation.
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 maxPathLength(vector<vector<int>>& coordinates, int k) {4 const int xk = coordinates[k][0];5 const int yk = coordinates[k][1];6 vector<pair<int, int>> leftCoordinates;7 vector<pair<int, int>> rightCoordinates;8 9 for (const vector<int>& coordinate : coordinates) {10 const int x = coordinate[0];11 const int y = coordinate[1];12 if (x < xk && y < yk)13 leftCoordinates.emplace_back(x, y);14 else if (x > xk && y > yk)15 rightCoordinates.emplace_back(x, y);16 }17 18 return 1 + lengthOfLIS(leftCoordinates) + lengthOfLIS(rightCoordinates);19 }20 21 private:22 23 int lengthOfLIS(vector<pair<int, int>>& coordinates) {24 ranges::sort(coordinates, ranges::less{},25 [](const pair<int, int>& coordinate) {26 const auto& [x, y] = coordinate;27 return pair<int, int>{x, -y};28 });29 30 31 vector<int> tails;32 for (const auto& [_, y] : coordinates)33 if (tails.empty() || y > tails.back())34 tails.push_back(y);35 else36 tails[firstGreaterEqual(tails, y)] = y;37 return tails.size();38 }39 40 int firstGreaterEqual(const vector<int>& arr, int target) {41 return ranges::lower_bound(arr, target) - arr.begin();42 }43};44