Problem solution · C++

K Highest Ranked Items Within a Price Range

K Highest Ranked Items Within a Price Range: a C++ solution using breadth-first search. Learn the idea, check the complexity, and read the full code, with credit to walkccc LeetCode Solutions.

Technique
Breadth-first search
Source
walkccc LeetCode Solutions
Length
63 lines
Start with the idea.

Try the problem first. If you get stuck, read the approach below, then write your own solution. The full code is at the bottom.

Approach

Breadth-first search

For K Highest Ranked Items Within a Price Range, the implementation explores reachable states in layers, which is the standard shape for unweighted shortest paths and minimum-step transitions.

  1. Model each valid configuration as a state and each legal move as an edge.
  2. Seed the queue with the starting state and mark it immediately.
  3. Expand each state once, recording distance or reachability for unseen neighbours.

Code notes

  • 63 lines of C++ from the credited upstream file 2146.cpp.
  • The implementation visibly relies on sequence storage, work queue.
  • 4 loop blocks detected.

Complexity

Verify that each state and transition is processed only a bounded number of times; that determines the traversal cost.

Check the problem constraints before deciding whether this complexity will pass.

Source

Code and credit

This code comes from walkccc LeetCode Solutions by P.-Y. Chen (walkccc) and is used under the MIT licence.

Full codeK Highest Ranked Items Within a Price Range · C++C++
Use this to learn the idea, then write your own version.
class Solution { public:  vector<vector<int>> highestRankedKItems(vector<vector<int>>& grid,                                          vector<int>& pricing,                                          vector<int>& start, int k) {    constexpr int kDirs[4][2] = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};    const int m = grid.size();    const int n = grid[0].size();    const int low = pricing[0];    const int high = pricing[1];    const int row = start[0];    const int col = start[1];    vector<vector<int>> ans;     if (low <= grid[row][col] && grid[row][col] <= high) {      ans.push_back({row, col});      if (k == 1)        return ans;    }     queue<pair<int, int>> q{{{row, col}}};    vector<vector<bool>> seen(m, vector<bool>(n));    seen[row][col] = true;  // Mark as visited.     while (!q.empty()) {      vector<vector<int>> neighbors;      for (int sz = q.size(); sz > 0; --sz) {        const auto [i, j] = q.front();        q.pop();        for (const auto& [dx, dy] : kDirs) {          const int x = i + dx;          const int y = j + dy;          if (x < 0 || x == m || y < 0 || y == n)            continue;          if (!grid[x][y] || seen[x][y])            continue;          if (low <= grid[x][y] && grid[x][y] <= high)            neighbors.push_back({x, y});          q.emplace(x, y);          seen[x][y] = true;        }      }      ranges::sort(neighbors, [&](const vector<int>& a, const vector<int>& b) {        const int x1 = a[0];        const int y1 = a[1];        const int x2 = b[0];        const int y2 = b[1];        if (grid[x1][y1] != grid[x2][y2])          return grid[x1][y1] < grid[x2][y2];        return x1 == x2 ? y1 < y2 : x1 < x2;      });      for (const vector<int>& neighbor : neighbors) {        if (ans.size() < k)          ans.push_back(neighbor);        if (ans.size() == k)          return ans;      }    }     return ans;  }}; 

Did this explanation save you time? I'm a Grade 11 student building this free library to make difficult algorithms easier to understand.

Buy me a coffee ↗