码迷,mamicode.com
首页 > 其他好文 > 详细

Max Sum of Rectangle No Larger Than K

时间:2016-06-27 12:08:32      阅读:126      评论: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
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!