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