最简单的枚举:
import java.util.Scanner;
//朴素
public class L1 {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
int m=sc.nextInt();
int[][] a=new int[55][55];
int ans=Integer.MIN_VALUE;
for(int i=0;i<n;i++) {
for(int j=0;j<m;j++)
a[i][j]=sc.nextInt();
}
for(int up=0;up<n;up++) {
for(int down=up;down<n;down++) {
for(int left=0;left<m;left++) {
for(int right=left;right<m;right++) {
int temp=0;
for(int i=up;i<=down;i++) {
for(int j=left;j<=right;j++) {
temp+=a[i][j];
}
}
if(temp>ans)
ans=temp;
}
}
}
}
System.out.println(ans);
}
}
输入:
3 3
2 -4 1
-1 2 1
4 -2 2
输出:
6
另一种利用前缀和的方式: