首页 > 代码库 > Leetcode: Max Sum of Rectangle No Larger Than K

Leetcode: 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:
Given matrix = [
  [1,  0, 1],
  [0, -2, 3]
]
k = 2
The answer is 2. 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?

The naive solution is brute-force, which is O((mn)^2). In order to be more efficient, I tried something similar to Kadane‘s algorithm. The only difference is that here we have upper bound restriction K. Here‘s the easily understanding video link for the problem "find the max sum rectangle in 2D array": Maximum Sum Rectangular Submatrix in Matrix dynamic programming/2D kadane (Trust me, it‘s really easy and straightforward).

Once you are clear how to solve the above problem, the next step is to find the max sum no more than K in an array. This can be done within O(nlogn), and you can refer to this article: max subarray sum no more than k.   This can be done using TreeSet.

 

For the solution below, I assume that the number of rows is larger than the number of columns. Thus in general time complexity is O[min(m,n)^2 * max(m,n) * log(max(m,n))], space O(max(m, n)).

假设col<row,下面的意思就是维护一个size为row的 sum数组。 每次iteration这个sum数组用来存某几个col叠加在一起的和(就是某一个rectangle的sum),然后在其中用treeSet找出当前最大的rectangle sum,时间复杂度是row*(log(row)). 所有iteration完成就得到最终答案,iteration数目是O(col^2), 所以总时间复杂度是O(col^2*row*log(row))。

 1 public class Solution {
 2     public int maxSumSubmatrix(int[][] matrix, int k) {
 3         if (matrix==null || matrix.length==0 || matrix[0].length==0) return Integer.MIN_VALUE;
 4         int res = Integer.MIN_VALUE;
 5         
 6         int row = matrix.length;
 7         int col = matrix[0].length;
 8         int m = Math.min(row, col);
 9         int n= Math.max(row, col);
10         boolean moreCol = col > row;
11         
12         for (int i=0; i<m; i++) {
13             int[] sum = new int[n];
14             for (int j=i; j<m; j++) {
15                 TreeSet<Integer> set = new TreeSet<Integer>();
16                 int val = 0;
17                 set.add(0);
18                 for (int l=0; l<n; l++) {
19                     sum[l] += moreCol? matrix[j][l] : matrix[l][j];
20                     val += sum[l];
21                     Integer oneSum = set.ceiling(val-k);
22                     if (oneSum != null) {
23                         res = Math.max(res, val-oneSum);
24                     }
25                     set.add(val);
26                 }
27             }
28         }
29         return res;
30     }
31 }

 

Leetcode: Max Sum of Rectangle No Larger Than K