JIAKAOBO

LeetCode

venmo
wechat

感谢赞助!

  • ㊗️
  • 大家
  • offer
  • 多多!

Problem

Given an m x n matrix matrix and an integer k, return the max sum of a rectangle in the matrix such that its sum is no larger than k.

It is guaranteed that there will be a rectangle with a sum no larger than k.

Example 1:

img

Input: matrix = [[1,0,1],[0,-2,3]], k = 2
Output: 2
Explanation: Because the sum of the blue rectangle [[0, 1], [-2, 3]] is 2, and 2 is the max number no larger than k (k = 2).

Example 2:

Input: matrix = [[2,2,-1]], k = 3
Output: 3

Code

class Solution {
    public int maxSumSubmatrix(int[][] matrix, int k) {
        int m = matrix.length;
        int n = matrix[0].length;
        int res = Integer.MIN_VALUE;

        for (int left = 0; left < n; left++){
            int[] sums = new int[m];
            for(int right = left; right < n; right++){
                for(int i = 0; i < m; i++){
                    sums[i] += matrix[i][right];
                }
                // 和求最大和不同,不能使用kadane方法
                // 这是Kadane方法的变形
                TreeSet<Integer> set = new TreeSet<>();
                set.add(0);
                int cur = 0;
                for(int sum : sums){
                    // curr是累加和
                    cur += sum;
                    // curr - k <= num
                    // curr - num <= k
                    Integer num = set.ceiling(cur - k);
                    if(num != null){
                        res = Math.max(res, cur - num);
                    }
                    set.add(cur);
                }
            }
        }

        return res;
    }
}