Approach
Sorting and greedy selection
For Minimize Maximum Value in a Grid, the implementation first exposes a useful order, then scans that order while making locally justified choices.
- Choose the key that reveals the greedy or grouping structure.
- Sort the relevant records by that key.
- Scan in order, maintaining the invariant that makes each local choice safe.
Code notes
- 28 lines of Java from the credited upstream file 2371.java.
- The implementation visibly relies on sequence storage.
- 3 loop blocks detected.
Complexity
Sorting is typically the dominant term unless the subsequent scan uses a more expensive nested operation.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
1class Solution {2 public int[][] minScore(int[][] grid) {3 final int m = grid.length;4 final int n = grid[0].length;5 int[][] ans = new int[m][n];6 List<int[]> valAndIndices = new ArrayList<>();7 int[] rows = new int[m]; 8 int[] cols = new int[n]; 9 10 for (int i = 0; i < m; ++i)11 for (int j = 0; j < n; ++j)12 valAndIndices.add(new int[] {grid[i][j], i, j});13 14 Collections.sort(valAndIndices, Comparator.comparingInt(valAndIndex -> valAndIndex[0]));15 16 for (int[] valAndIndex : valAndIndices) {17 final int i = valAndIndex[1];18 final int j = valAndIndex[2];19 final int nextAvailable = Math.max(rows[i], cols[j]) + 1;20 ans[i][j] = nextAvailable;21 rows[i] = nextAvailable;22 cols[j] = nextAvailable;23 }24 25 return ans;26 }27}28