首页 > 代码库 > 2.15 子数组之和的最大值(二维)

2.15 子数组之和的最大值(二维)

题目:给定一个二维数组,求这个二维数组的子数组之和的最大值。


分析:将二维降低到一维的情况。



代码:

#include <iostream>

const int MAXN = 10000;
const int INF = 100000000;

using namespace std;

int B[MAXN][MAXN], PS[MAXN][MAXN];
int n, m;

int BC(int first, int last, int liehao) {
	return PS[last][liehao] - PS[first-1][liehao] - PS[last][liehao-1] + PS[first-1][liehao-1];
}

int MaxSum(int n, int m) {
	int ret = -INF;
	int Start = 0, All = 0;
	for(int a = 1; a <= n; ++a) {
		for(int c = a; c <= n; ++c) {
			Start = BC(a, c, m);
			All = BC(a, c, m);
			for(int i = m-1;  i >= 1; --i) {
				if(Start < 0) Start = 0;
				Start += BC(a, c, i);
				if(Start > All) All = Start;
			}
			if(All > ret) ret = All;
		}
	} 
	return ret;
}

int main() {
	cin >> n >> m;
	for(int i = 1; i <= n; ++i) {
		for(int j = 1; j <= m; ++j) {
			cin >> B[i][j];
		}
	}
	//计算二维数组PS,方便后期在O(1)的时间内求出PS[i][j]
	for(int i = 0; i <= n; ++i) PS[i][0] = 0;
	for(int i = 0; i <= m; ++i) PS[0][i] = 0;
	for(int i = 1; i <= n; ++i) {
		for(int j = 1; j <= m; ++j) {
			PS[i][j] = PS[i][j-1] + PS[i-1][j] - PS[i-1][j-1] + B[i][j];
		}
	}
	cout << MaxSum(n, m) << endl;
	return 0;
}


2.15 子数组之和的最大值(二维)