Approach
Sorting and greedy selection
For Maximum Value Sum by Placing Three Rooks II, 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
- 62 lines of Java from the credited upstream file 3257.java.
- The implementation visibly relies on sequence storage, hash lookup, ordered lookup.
- 9 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 3 public long maximumValueSum(int[][] board) {4 final int m = board.length;5 final int n = board[0].length;6 long ans = Long.MIN_VALUE;7 List<int[]>[] rows = new ArrayList[m];8 List<int[]>[] cols = new ArrayList[n];9 Set<int[]> rowSet = new HashSet<>();10 Set<int[]> colSet = new HashSet<>();11 Set<int[]> boardSet = new HashSet<>();12 13 for (int i = 0; i < m; ++i)14 rows[i] = new ArrayList<>();15 16 for (int j = 0; j < n; ++j)17 cols[j] = new ArrayList<>();18 19 for (int i = 0; i < m; ++i)20 for (int j = 0; j < n; ++j) {21 int[] cell = new int[] {board[i][j], i, j};22 rows[i].add(cell);23 cols[j].add(cell);24 }25 26 Comparator<int[]> comparator = Comparator.comparingInt(a -> - a[0]);27 28 for (List<int[]> row : rows) {29 row.sort(comparator);30 rowSet.addAll(row.subList(0, Math.min(3, row.size())));31 }32 33 for (List<int[]> col : cols) {34 col.sort(comparator);35 colSet.addAll(col.subList(0, Math.min(3, col.size())));36 }37 38 boardSet.addAll(rowSet);39 boardSet.retainAll(colSet);40 41 42 43 List<int[]> topNine = new ArrayList<>(boardSet);44 topNine.sort(comparator);45 topNine = topNine.subList(0, Math.min(9, topNine.size()));46 47 for (int i = 0; i < topNine.size(); ++i)48 for (int j = i + 1; j < topNine.size(); ++j)49 for (int k = j + 1; k < topNine.size(); ++k) {50 int[] t1 = topNine.get(i);51 int[] t2 = topNine.get(j);52 int[] t3 = topNine.get(k);53 if (t1[1] == t2[1] || t1[1] == t3[1] || t2[1] == t3[1] || 54 t1[2] == t2[2] || t1[2] == t3[2] || t2[2] == t3[2])55 continue;56 ans = Math.max(ans, (long) t1[0] + t2[0] + t3[0]);57 }58 59 return ans;60 }61}62