【原题】
题目链接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).
【分析】
题目要去二维数组中子矩阵的最大和,这个和不超过k.
可以先分析一维数组的情况:
在下标为j的位置,curSum[j]表示从第一个元素到j的元素和为curSum[j],若在j之前的某个位置i,有curSum[j]-curSum[i]<=k,则子数组(i,j)符合题目要求 ,遍历所有元素,即可得到所有位置的curSum值和curSum[j]-curSum[i],并取最大即可。
代码中用到了set集合,用于保存curSum。
【Java】
public int maxSumSeq(int[] nums, int k){
int ret = Integer.MIN_VALUE;
if(nums.length==0) return 0;
int curSum = 0;
Set<Integer> set = new HashSet<Integer>();
set.add(0);
for (int i = 0; i < nums.length; i++) {
curSum+=nums[i];
int tempMax = Integer.MIN_VALUE;
for (Integer s : set) {
if(curSum-s<=k)
tempMax = Math.max(tempMax, curSum-s);
}
ret = Math.max(tempMax, ret);
set.add(curSum);
}
return ret;
}
对于题目给的二维数组,可以转成一维数组。
以列为遍历对象,并且是双层遍历,这样就划分出了一个子二维数组,其行数为原数组的行数,列数为双层遍历的所夹的列数。把一行看成一个 元素,这样就转成了长度为row的一维数组,可以得到这个一维数组满足要求的最大值。当遍历完所有列之后即可得到原二维数组的最后结果。
【Java】
public class Solution {
public int maxSumSubmatrix(int[][] matrix, int k) {
int row = matrix.length;
int col = matrix[0].length;
int ret = Integer.MIN_VALUE;
for (int i = 0; i < col; i++) {
int[] sum= new int[row];
for (int j = i; j < col; j++) {
for (int r = 0; r < row; r++) {
sum[r] += matrix[r][j];
}
ret = Math.max(ret, maxSumSeq(sum,k));
}
}
return ret;
}
public int maxSumSeq(int[] nums, int k){
int ret = Integer.MIN_VALUE;
if(nums.length==0) return 0;
int curSum = 0;
Set<Integer> set = new HashSet<Integer>();
set.add(0);
for (int i = 0; i < nums.length; i++) {
curSum+=nums[i];
int tempMax = Integer.MIN_VALUE;
for (Integer s : set) {
if(curSum-s<=k)
tempMax = Math.max(tempMax, curSum-s);
}
ret = Math.max(tempMax, ret);
set.add(curSum);
}
return ret;
}
}