[LeetCode] Minimize Maximum Value in a Grid

2371. Minimize Maximum Value in a Grid

You are given an m x n integer matrix grid containing distinct positive integers.

You have to replace each integer in the matrix with a positive integer satisfying the following conditions:

  • The relative order of every two elements that are in the same row or column should stay the same after the replacements.
  • The maximum number in the matrix after the replacements should be as small as possible.

The relative order stays the same if for all pairs of elements in the original matrix such that grid[r1][c1] > grid[r2][c2] where either r1 == r2 or c1 == c2, then it must be true that grid[r1][c1] > grid[r2][c2] after the replacements.

For example, if grid = [[2, 4, 5], [7, 3, 9]] then a good replacement could be either grid = [[1, 2, 3], [2, 1, 4]] or grid = [[1, 2, 3], [3, 1, 4]].

Return the resulting matrix. If there are multiple answers, return any of them.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class Solution {
public:
vector<vector<int>> minScore(vector<vector<int>>& grid) {
int n = grid.size(), m = grid[0].size();
vector<int> r(n), c(m);
priority_queue<array<int,3>, vector<array<int,3>>, greater<array<int,3>>> Q;
for(int i = 0; i < n; i++) {
for(int j = 0; j < m; j++) {
Q.push({grid[i][j], i,j});
}
}
while(!Q.empty()) {
auto [_, y,x] = Q.top(); Q.pop();
int now = max(r[y], c[x]) + 1;
r[y] = c[x] = grid[y][x] = now;
}
return grid;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/08/11/PS/LeetCode/minimize-maximum-value-in-a-grid/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.