Minimize Maximum Value in a Grid

Sort all cells by value, then assign each its rank under "max(row max so far, col max so far) + 1".

Hard
Time O(m*n log(m*n)) Space O(m*n)
LeetCode
4 min read
sorting greedy matrix

Problem#

Given an m x n grid of positive integers, replace each cell with a new positive integer so that (a) the relative ordering within each row and each column is preserved, and (b) the maximum value in the result is minimized. Return the resulting grid.

Examples#

  • grid = [[3,1],[2,5]][[2,1],[1,2]]
  • grid = [[10]][[1]]

Constraints#

  • 1 <= m, n <= 1000, 1 <= grid[i][j] <= 10^9. All grid entries are distinct.

Approach#

Sort all cells by value. Process them in that order, assigning each the smallest valid rank: max(rowMax[r], colMax[c]) + 1, then update rowMax[r] and colMax[c].

Solution#

Minimize Maximum Value in a Grid
class Solution {
public:
vector<vector<int>> minScore(vector<vector<int>>& grid) {
int m = grid.size(), n = grid[0].size();
vector<tuple<int,int,int>> cells;
cells.reserve(m * n);
for (int i = 0; i < m; ++i)
for (int j = 0; j < n; ++j)
cells.push_back({grid[i][j], i, j});
sort(cells.begin(), cells.end());
vector<int> rowMax(m, 0), colMax(n, 0);
vector<vector<int>> ans(m, vector<int>(n, 0));
for (auto& [_, i, j] : cells) {
int v = max(rowMax[i], colMax[j]) + 1;
ans[i][j] = v;
rowMax[i] = colMax[j] = v;
}
return ans;
}
};

Editorial#

Order-preservation only requires each cell to be larger than its predecessors in the same row and column. Processing in sorted order keeps things consistent. Greedy minimum-feasible rank assignment provably yields the globally minimum max value.

Complexity#

  • Time: O(mn log(mn)).
  • Space: O(m*n).

Concept revision#

Search ESC

Keyboard shortcuts

Shortcuts are disabled while typing in inputs.