晨哥Leetcode 363. Max Sum of Rectangle No Larger Than K

Given a non-empty 2D matrix matrix and an integer k, find the max sum of a rectangle in the matrix such that its sum is no larger than k.
Example:
Input: matrix = [[1,0,1],[0,-2,3]], k = 2
Output: 2
Explanation: Because the sum of rectangle [[0, 1], [-2, 3]] is 2,
and 2 is the max number no larger than k (k = 2).
Note:
The rectangle inside the matrix must have an area > 0.
What if the number of rows is much larger than the number of columns?

解析:
这题跟这道题几乎一样:
leetcode 1074. Number of Submatrices That Sum to Target
总共有0 … n-1个列,枚举两个列的区间i, j(可以是同一个列, i<=j)
我们可以通过提前计算,得到每一行的prefix sum, 很容易得到每一行在i …j之间的数的和
这个时候我们把列压缩成一个数了,从上往下一行一行看,这又变成了一维的了
一维的这个问题求no more than k,用treeset是最方便的,详见注释
(相等用hashset, 不小于k/不大于k之类的问题用treeset搜索

public int maxSumSubmatrix(int[][] a, int k) {
        if(a.length == 0 || a[0].length == 0) return 0;
        int m = a.length, n = a[0].length; // m* n
        for(int i = 0; i < m; i++) {
            for(int j = 1; j < n; j++) {
                a[i][j] += a[i][j-1];//对每行分别计算prefix sum,第i行前j的数的和
            }
        }
        int max = Integer.MIN_VALUE;
        for(int i = 0; i < n; i++) {
            for(int j = i; j < n; j++) {//枚举列i...j,  i<=j
                TreeSet set = new TreeSet();
                set.add(0);//prefix sum问题经常需要在前面加个0,因为我们总是要算差值,如果从0开始的subarray sum就是prefix sum - 0
                int sum = 0;
                for(int x = 0; x < m; x++) {
                    int cur = i == 0 ? a[x][j] : a[x][j] - a[x][i-1];//current row sum between i,j       
                    sum+=cur;//prefix sum 到该行
                    Integer ceiling = set.ceiling(sum - k);// ceiling的规律 sum - k <= ceiling 那么sum-ceilng <=k
                    set.add(sum);
                    if(ceiling != null) {
                        max = Math.max(max, sum - ceiling);//sum-ceiling就是subarray的和
                    }
                }
                
            }
        }
       

你可能感兴趣的:(treeset/map)