1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42
| class Solution { public int maxSumSubmatrix(int[][] matrix, int k) { int m = matrix.length, n = matrix[0].length;
int[][] sumMatrix = new int[m + 1][n + 1];
for (int i = 1; i <= m; i++) { for (int j = 1; j <= n; j++) { sumMatrix[i][j] = sumMatrix[i - 1][j] + sumMatrix[i][j - 1] - sumMatrix[i - 1][j - 1] + matrix[i - 1][j - 1]; } }
int maxSum = Integer.MIN_VALUE;
for (int startRow = 1; startRow <= m; startRow++) { for (int endRow = startRow; endRow <= m; endRow++) { TreeSet<Integer> set = new TreeSet<>(); set.add(0);
for (int endCol = 1; endCol <= n; endCol++) { int leftmostToRightAreaSum = sumMatrix[endRow][endCol] - sumMatrix[startRow - 1][endCol]; Integer leftAreaSum = set.ceiling(leftmostToRightAreaSum - k); if (leftAreaSum != null) { int rightAreaSum = leftmostToRightAreaSum - leftAreaSum; maxSum = Math.max(maxSum, rightAreaSum); } set.add(leftmostToRightAreaSum); } } }
return maxSum; } }
|
References
363. Max Sum of Rectangle No Larger Than K