|
| 1 | +package g3201_3300.s3257_maximum_value_sum_by_placing_three_rooks_ii; |
| 2 | + |
| 3 | +// #Hard #Array #Dynamic_Programming #Matrix #Enumeration |
| 4 | +// #2024_08_20_Time_18_ms_(99.59%)_Space_74.2_MB_(66.81%) |
| 5 | + |
| 6 | +import java.util.Arrays; |
| 7 | + |
| 8 | +public class Solution { |
| 9 | + public long maximumValueSum(int[][] board) { |
| 10 | + int n = board.length; |
| 11 | + int m = board[0].length; |
| 12 | + int[][] tb = new int[n][m]; |
| 13 | + tb[0] = Arrays.copyOf(board[0], m); |
| 14 | + for (int i = 1; i < n; i++) { |
| 15 | + for (int j = 0; j < m; j++) { |
| 16 | + tb[i][j] = Math.max(tb[i - 1][j], board[i][j]); |
| 17 | + } |
| 18 | + } |
| 19 | + int[][] bt = new int[n][m]; |
| 20 | + bt[n - 1] = Arrays.copyOf(board[n - 1], m); |
| 21 | + for (int i = n - 2; i >= 0; i--) { |
| 22 | + for (int j = 0; j < m; j++) { |
| 23 | + bt[i][j] = Math.max(bt[i + 1][j], board[i][j]); |
| 24 | + } |
| 25 | + } |
| 26 | + long ans = Long.MIN_VALUE; |
| 27 | + for (int i = 1; i < n - 1; i++) { |
| 28 | + int[][] max3Top = getMax3(tb[i - 1]); |
| 29 | + int[][] max3Cur = getMax3(board[i]); |
| 30 | + int[][] max3Bottom = getMax3(bt[i + 1]); |
| 31 | + for (int[] topCand : max3Top) { |
| 32 | + for (int[] curCand : max3Cur) { |
| 33 | + for (int[] bottomCand : max3Bottom) { |
| 34 | + if (topCand[1] != curCand[1] |
| 35 | + && topCand[1] != bottomCand[1] |
| 36 | + && curCand[1] != bottomCand[1]) { |
| 37 | + long cand = (long) topCand[0] + curCand[0] + bottomCand[0]; |
| 38 | + ans = Math.max(ans, cand); |
| 39 | + } |
| 40 | + } |
| 41 | + } |
| 42 | + } |
| 43 | + } |
| 44 | + return ans; |
| 45 | + } |
| 46 | + |
| 47 | + private int[][] getMax3(int[] row) { |
| 48 | + int m = row.length; |
| 49 | + int[][] ans = new int[3][2]; |
| 50 | + Arrays.fill(ans, new int[] {Integer.MIN_VALUE, -1}); |
| 51 | + for (int j = 0; j < m; j++) { |
| 52 | + if (row[j] >= ans[0][0]) { |
| 53 | + ans[2] = ans[1]; |
| 54 | + ans[1] = ans[0]; |
| 55 | + ans[0] = new int[] {row[j], j}; |
| 56 | + } else if (row[j] >= ans[1][0]) { |
| 57 | + ans[2] = ans[1]; |
| 58 | + ans[1] = new int[] {row[j], j}; |
| 59 | + } else if (row[j] > ans[2][0]) { |
| 60 | + ans[2] = new int[] {row[j], j}; |
| 61 | + } |
| 62 | + } |
| 63 | + return ans; |
| 64 | + } |
| 65 | +} |
0 commit comments