- Define the priority key and whether the smallest or largest item should lead.
- Push each candidate when it becomes eligible.
- Discard stale entries when necessary and process the best live candidate.
Code notes
- 66 lines of C++ from the credited upstream file 2503.cpp.
- The implementation visibly relies on sequence storage, work queue.
- 4 loop blocks detected.
Complexity
Count heap pushes and pops; each normally contributes a logarithmic factor in the heap size.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
1struct IndexedQuery {2 int queryIndex;3 int query;4};5 6struct T {7 int i;8 int j;9 int val; 10};11 12class Solution {13 public:14 vector<int> maxPoints(vector<vector<int>>& grid, vector<int>& queries) {15 constexpr int kDirs[4][2] = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};16 const int m = grid.size();17 const int n = grid[0].size();18 vector<int> ans(queries.size());19 auto compare = [](const T& a, const T& b) { return a.val > b.val; };20 priority_queue<T, vector<T>, decltype(compare)> minHeap(compare);21 vector<vector<bool>> seen(m, vector<bool>(n));22 23 minHeap.emplace(0, 0, grid[0][0]);24 seen[0][0] = true;25 int accumulate = 0;26 27 for (const auto& [queryIndex, query] : getIndexedQueries(queries)) {28 while (!minHeap.empty()) {29 const auto [i, j, val] = minHeap.top();30 minHeap.pop();31 if (val >= query) {32 33 34 minHeap.emplace(i, j, val);35 break;36 }37 ++accumulate;38 for (const auto& [dx, dy] : kDirs) {39 const int x = i + dx;40 const int y = j + dy;41 if (x < 0 || x == m || y < 0 || y == n)42 continue;43 if (seen[x][y])44 continue;45 minHeap.emplace(x, y, grid[x][y]);46 seen[x][y] = true;47 }48 }49 ans[queryIndex] = accumulate;50 }51 52 return ans;53 }54 55 private:56 vector<IndexedQuery> getIndexedQueries(const vector<int>& queries) {57 vector<IndexedQuery> indexedQueries;58 for (int i = 0; i < queries.size(); ++i)59 indexedQueries.push_back({i, queries[i]});60 ranges::sort(61 indexedQueries, ranges::less{},62 [](const IndexedQuery& indexedQuery) { return indexedQuery.query; });63 return indexedQueries;64 }65};66