public class Solution { public int maxSumSubmatrix(int[][] matrix, int k) { if (matrix.length == 0 || matrix[0].length == 0) { return 0; } int result = Integer.MIN_VALUE; int row = matrix.length, col = matrix[0].length; int m = Math.min(row, col); int n = Math.max(row, col); boolean isCol = row > col ? true : false; for (int i = 0; i < m; i++) { int[] sum = new int[n]; for (int j = i; j >= 0; j--) { int val = 0; TreeSet<Integer> set = new TreeSet<>(); set.add(0); for (int l = 0; l < n; l++) { sum[l] += isCol ? matrix[l][j] : matrix[j][l]; val += sum[l]; Integer subresult = set.ceiling(val - k); if (subresult != null) { result = Math.max(result, val - subresult); } set.add(val); } } } return result; } }
1. Set does not have ceiling method. Directly use TreeSet
2. ceiling > value - k, so value - ceiling < k.
3. Put 0 into set first since 0 should be the exactly upper bound.