Given a two-dimensional array of positive and negative integers, a sub-rectangle is any contiguous sub-array of size 1*1 or greater located within the whole array. The sum of a rectangle is the sum of all the elements in that rectangle. In this problem the sub-rectangle with the largest sum is referred to as the maximal sub-rectangle.
As an example, the maximal sub-rectangle of the array:
0 -2 -7 0
9 2 -6 2
-4 1 -4 1
-1 8 0 -2
is in the lower left corner:
9 2
-4 1
-1 8
and has a sum of 15.
The input consists of an N * N array of integers. The input begins with a single positive integer N on a line by itself, indicating the size of the square two-dimensional array. This is followed by N^2 integers separated by whitespace (spaces and newlines). These are the N^2 integers of the array, presented in row-major order. That is, all numbers in the first row, left to right, then all numbers in the second row, left to right, etc. N may be as large as 100. The numbers in the array will be in the range [-127,127].
Output the sum of the maximal sub-rectangle.
4
0 -2 -7 0
9 2 -6 2
-4 1 -4 1
-1 8 0 -2
15
Greater New York 2001
无长度限制的最大子段和问题是一个经典问题,只需 O ( N ) O(N) O(N) 扫描该数列,不断把新的数加入子段,当子段和变成负数时,把当前的整个子段清空。扫描过程中出现过的最大子段和即为所求。
最大子矩阵和,就想办法将二维转成一维进行处理。将能组成矩阵的数或者和转成一维。
#include
using namespace std;
const int N = 105;
int matrix[N][N]; //二维矩阵
int temp[N]; //一维
//无长度限制的最长子段和
int maxSubSequenceSum(int *arr, int n) {
int sum = 0;
int ans = (int)-1e9;
for (int i = 1; i <= n; i++) {
if (sum + arr[i] < 0) {
sum = 0;
} else {
sum += arr[i];
ans = max(ans, sum);
}
}
return ans;
}
int main() {
int n;
cin >> n;
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= n; j++) {
cin >> matrix[i][j];
}
}
int ans = (int)-1e9;
//能组成矩形的相邻数据,二维转一维
for (int i = 1; i <= n; i++) { //每行选择的数的开始位置
for (int j = i; j <= n; j++) { //每行选择的数的终止位置
for (int k = 1; k <= n; k++) { //枚举行(转一维)
temp[k] = 0;
for (int m = i; m <= j; m++) {
temp[k] += matrix[k][m];
}
}
ans = max(ans, maxSubSequenceSum(temp, n));
}
}
cout << ans << endl;
return 0;
}