#2146
Medium Algorithms K highest ranked items within a price range
Array Breadth-First Search Sorting Heap (Priority Queue) Matrix
46.4% acceptance
Feb 25, 2026
532
168
You are given a 0-indexed 2D integer array grid of size m x n that represents a map of the items in a shop. The integers in the grid represent the following:
0 represents a wall that you cannot pass through.
1 represents an empty cell that you can freely move to and from.
All other positive integers represent the price of an item in that cell. You may also freely move to and from these item cells.
You are also given integer arrays pricing and start where pricing = [low, high] and start = [row, col] indicates that you start at the position (row, col) and are interested only in items with a price in the range of [low, high] (inclusive). You are further given an integer k.
Return the k highest-ranked items within the price range sorted by their rank (highest to lowest). If there are fewer than k reachable items within the price range, return all of them.
Solution
Rust
Time O(n * m)
Space O(n * m)
impl Solution {
pub fn highest_ranked_k_items(
grid: Vec<Vec<i32>>,
pricing: Vec<i32>,
start: Vec<i32>,
k: i32,
) -> Vec<Vec<i32>> {
use std::collections::VecDeque;
let m = grid.len();
let n = grid[0].len();
let (sr, sc) = (start[0] as usize, start[1] as usize);
let (lo, hi) = (pricing[0], pricing[1]);
let mut visited = vec![vec![false; n]; m];
let mut queue = VecDeque::new();
queue.push_back((sr, sc, 0i32));
visited[sr][sc] = true;
let mut items: Vec<(i32, i32, i32, i32)> = Vec::new(); // (dist, price, row, col)
while let Some((r, c, d)) = queue.pop_front() {
let price = grid[r][c];
if price >= lo && price <= hi {
items.push((d, price, r as i32, c as i32));
}
for (dr, dc) in [(-1i32, 0i32), (1, 0), (0, -1), (0, 1)] {
let nr = r as i32 + dr;
let nc = c as i32 + dc;
if nr >= 0 && nr < m as i32 && nc >= 0 && nc < n as i32 {
let (nr, nc) = (nr as usize, nc as usize);
if !visited[nr][nc] && grid[nr][nc] != 0 {
visited[nr][nc] = true;
queue.push_back((nr, nc, d + 1));
}
}
}
}
items.sort();
items.truncate(k as usize);
items
.into_iter()
.map(|(_, _, r, c)| vec![r, c])
.collect()
}
}