您的位置:首页 > 其它

Max Sum of Rectangle No Larger Than K

2016-06-27 11:30 441 查看
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
;
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.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: