思路
题目是要求子矩形的最大和。确定一个左上顶点和一个右下顶点可以确定一个矩形,要枚举这两个点,总的复杂度为N^4
为简化,可以选择枚举上边界和下边界,此时可以确定一个矩形区域,然后可以将问题转换为求一维数组的最大连续和。
import java.util.*;
class Main{
final static int INF = 0x3f3f3f3f;
public static void main(String[] args){
Scanner scanner = new Scanner(System.in);
int N = scanner.nextInt();
int mapp[][] = new int[N+1][N+1];
for(int i = 1; i <= N; i++){
for(int j = 1; j <= N; j++){
mapp[i][j] = scanner.nextInt();
mapp[i][j] += mapp[i-1][j];
}
}
int f[] = new int[N+1];
int ans = -INF;
//枚举上边和下边
for(int top = 0; top < N; top++){
for(int bottom = top + 1; bottom <= N; bottom++){
for(int col = 1; col <= N; col++){
f[col] = mapp[bottom][col] - mapp[top][col];
}
for(int col = 1; col <= N; col++){
//求最大连续和
if(f[col-1] > 0) f[col] = f[col-1] + f[col];
ans = max(ans, f[col]);
}
}
}
System.out.print(ans);
return;
}
public static int max(int a, int b){
return a > b ? a : b;
}
}