Max Sum of Rectangle No Larger Than K

Posted keepshuatishuati

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Max Sum of Rectangle No Larger Than K相关的知识,希望对你有一定的参考价值。

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.

以上是关于Max Sum of Rectangle No Larger Than K的主要内容,如果未能解决你的问题,请参考以下文章

Max Sum of Rectangle No Larger Than K

leetcode363. Max Sum of Rectangle No Larger Than K

363 Max Sum of Rectangle No Larger Than K 最大矩阵和不超过K

[LeetCode] Max Sum of Rectangle No Larger Than K 最大矩阵和不超过K

Max Sum of Max-K-sub-sequence

Oracle: MAX of SUM of each Group