Maximize adjacent land purchases within budget
Filed under OYO
Free read 2 of 3Confirm if cells must be connected strictly orthogonally (up, down, left, right) and whether all land components must be evaluated.
The question
Given a 2D matrix representing land prices and a specified budget, maximize the number of orthogonally connected land cells you can acquire.
Constraints
- Matrix dimensions N x M are between 1 and 50.
- Budget is a non-negative integer.
- Land prices are positive integers.
Examples
- Input
- matrix = [[1, 2], [3, 4]], budget = 5
- Output
- 2
- Why
- You can acquire cells with prices 1 and 2 or 1 and 3, giving a maximum connected component size of 2.
Approach
Confirm if cells must be connected strictly orthogonally (up, down, left, right) and whether all land components must be evaluated.
Generate all possible connected subsets of cells starting from every cell, calculate their total cost, and find the largest subset within budget. Highly exponential time complexity.
Since this resembles variations of region growing or knapsack on graphs, use Breadth-First Search (BFS) or Prim's-like expansion from each starting cell to greedily find the cheapest connected components up to the budget.
Budget is less than the minimum value in the matrix (return 0), or all cells fit within the budget.
Tips
- What they are testing: Test with disconnected components, budgets smaller than the minimum cell price, and a budget large enough to buy the entire grid.
- Common mistake: Treating the problem as a standard subset sum without enforcing the geometric connectivity constraint.
Related OYO questions
Collected from public candidate posts and coding forums. Updated Nov 2026.