#include <iostream>
using namespace std;
#define M 4
#define N 5
void initColSumArray(int src[][N], int dest[][N + 1]) {
for (int j = 1; j <= N; ++j) {
for (int i = 1; i <= M; ++i) {
dest[i][j] = dest[i - 1][j] + src[i - 1][j - 1];
}
}
}
int findMaxSumFromSubArray(int *ps, int begin, int end) {
int curSum = 0;
int maxSum = 0;
int hasNegative = false;
int len = end - begin + 1;
for (int i = begin - 1; i < len * 2 - 1 + begin; i++) {
if (i <= end && ps[i] < 0) {
hasNegative = true;
}
curSum = max(curSum + ps[i % len + 1], ps[i % len + 1]);
maxSum = max(curSum, maxSum);
if (i == end && !hasNegative) {
return maxSum;
}
}
return maxSum;
}
/*穷举所有上下边界,计算每个上下边界围成的矩形的每一列的和,
* 在用一维数组求连续子数组最大和的方式求解*/
int findMaxSumFromSubMatrix(int arr[][N], int bs[][N + 1]) {
int ps[N + 1] = { 0 };
//初始化每一个子矩形的列和
initColSumArray(arr, bs);
int curSum = 0;
int maxSum = 0;
for (int up = 1; up <= M; ++up) {
for (int down = 1; down <= M; ++down) {
for (int i = 1; i <= N; ++i) {
ps[i] = bs[down][i] - bs[up - 1][i];
}
}
if ((curSum = findMaxSumFromSubArray(ps, 1, N)) > maxSum) {
maxSum = curSum;
}
}
return maxSum;
}
int main() {
int arr[M][N] = { { 1, 2, -1, -4 - 20 }, { -8, -3, 4, 2, 1 }, { 3, 8, 10, 1,
3 }, { -4, -1, 1, 7, -6 } };
int bs[M + 1][N + 1] = { 0 };
cout << "maxSum: " << findMaxSumFromSubMatrix(arr, bs) << endl;
return 0;
}
首尾连接的二维数组中连续子数组的最大和
最新推荐文章于 2018-09-04 10:57:08 发布