首尾连接的二维数组中连续子数组的最大和

#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;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值