首页 > 其他 > 详细

Max Sum of Rectangle No Larger Than K

时间:2016-06-27 12:08:29      阅读:511      评论:0      收藏:0      [点我收藏+]
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

原文:http://www.cnblogs.com/shuashuashua/p/5619670.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!