题目:
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).
链接:https://leetcode.com/problems/max-sum-of-sub-matrix-no-larger-than-k/
在解决这个问题之前,我们先讨论最大子矩阵和的解法
求一个M*N的矩阵的最大子矩阵和。
比如在如下这个矩阵中:
0 -2 -7 0
9 2 -6 2
-4 1 -4 1
-1 8 0 -2
拥有最大和的子矩阵为:
9 2
-4 1
-1 8
其和为15。
源码:
#include
#include
#include
#include
#include
#include
#include
结果:
可以看到最大子矩阵和为15,从第1行到第3行,第0列到第1列!!!!
思路:
我们先确定行的范围,比如从第i行到第j行,然后对每一行进行向下累加,那么在i到j之间的行就变成1行,这个时候就可以用最大子段和的方法来求解!!!!
对于leetcode的这道题,唯一的区别在于我们把多行整理成一行的时候,这一行的数据我们要算任意两个元素之间的差!!!所以又要引入双重循环,所以我的解答的复杂度达到了
o(n^4),有待改进!!!
源码:
class Solution {
public:
int maxSumSubmatrix(vector>& matrix, int k) {
int diff = INT_MAX;
int near = -INT_MAX,h;
int row = matrix.size();
int col = matrix[0].size();
vector>psum = matrix;
//向下累加计算部分和
for (int i = 1; i < row; i++){
for (int j = 0; j < col; j++){
psum[i][j] = psum[i][j] + psum[i - 1][j];
}
}
vectorre(col, 0);
//利用最大字段和的思想
for (int i = 0; i < row; i++){//控制上方的行
for (int j = i; j sum(col, 0);
sum[0] = re[0];
for (h = 1; h < col; h++)sum[h] = sum[h-1]+re[h];
//双重循环
int temp_sum;
for (int m = 0; m < col; m++){
for (int h = m; h < col; h++){
if (m == 0)temp_sum = sum[h];
else temp_sum = sum[h] - sum[m - 1];
//比较
int temp_diff = k - temp_sum;
if (temp_diff >= 0){
if ( temp_diff< diff){
diff = temp_diff;
near = temp_sum;
}
}
}
}
}
}
return near;
}
};