Minimize Maximum Value in a Grid Problem
Description
LeetCode Problem 2371.
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[r_1][c_1] > grid[r_2][c_2] where either r_1 == r_2 or c_1 == c_2, then it must be true that grid[r_1][c_1] > grid[r_2][c_2] 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.
Example 1:

Input: grid = [[3,1],[2,5]]
Output: [[2,1],[1,2]]
Explanation: The above diagram shows a valid replacement.
The maximum number in the matrix is 2. It can be shown that no smaller value can be obtained.
Example 2:
Input: grid = [[10]]
Output: [[1]]
Explanation: We replace the only number in the matrix with 1.
Constraints:
m == grid.lengthn == grid[i].length1 <= m, n <= 10001 <= m * n <= 10^51 <= grid[i][j] <= 10^9gridconsists of distinct integers.
Solution
Approach: Process Cells From Small to Large
The values are distinct, so we can sort the cells by value. When a cell is handled, all smaller cells in its row and column already have their new values. The new value must be larger than all of them, and the smallest choice is one more than the largest new value in its row or column. Keep rowMax and colMax for that, and update them after assigning each cell. This gives every cell the smallest value it can have, so the maximum is minimal.
Complexity: O(mn log(mn)) time and O(mn) space.
class Solution:
def minScore(self, grid: List[List[int]]) -> List[List[int]]:
m, n = len(grid), len(grid[0])
nums = [(v, i, j) for i, row in enumerate(grid) for j, v in enumerate(row)]
nums.sort()
row_max = [0] * m
col_max = [0] * n
ans = [[0] * n for _ in range(m)]
for _, i, j in nums:
ans[i][j] = max(row_max[i], col_max[j]) + 1
row_max[i] = col_max[j] = ans[i][j]
return ans