363. Max Sum of Rectangle No Larger Than K - jiejackyzhang/leetcode-note GitHub Wiki
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?
解题思路为:
- 考虑1D array的情形,我们可以将0~i(0<=i<len)的和保存起来,然后对于每个index,可用binary search找前面的index,两者之差不大于k。
- 转换到2D matrix的情形,我们可以sum up all values from row i to row j,用一个1D array保存这些和,然后可以用1D array的方法来解。
外部两个循环为O(row^2),内部1D解法采用binary search,为O((col)log(col)),因此总的时间复杂度为O(row^2*(col)log(col))。
若row比col大,则我们可以取min(row, col)为外部循环。 令m = min(row, col),n = max(row, col),则总的时间复杂度为O(m^2*nlogn)。
public class Solution {
public int maxSumSubmatrix(int[][] matrix, int k) {
if(matrix == null || matrix.length == 0 || matrix[0] == null || matrix[0].length == 0) return 0;
int row = matrix.length;
int col = matrix[0].length;
int m = Math.min(row, col);
int n = Math.max(row, col);
boolean colIsLarger = col > row;
int res = Integer.MIN_VALUE;
for(int i = 0; i < m; i++) {
int[] arr = new int[n];
// sum from row j to row i
for(int j = i; j >= 0; j--) {
int val = 0;
TreeSet<Integer> set = new TreeSet<>();
set.add(0); // res can start from index 0
for(int t = 0; t < n; t++) {
arr[t] = arr[t] + (colIsLarger ? matrix[j][t] : matrix[t][j]);
// sum from 0 to t
val = val + arr[t];
Integer subres = set.ceiling(val - k);
if(subres != null) res = Math.max(res, val - subres);
set.add(val);
}
}
}
return res;
}
}