最大和
时间限制:1000 ms | 内存限制:65535 KB
难度:5
-
描述
-
给定一个由整数组成二维矩阵(r*c),现在需要找出它的一个子矩阵,使得这个子矩阵内的所有元素之和最大,并把这个子矩阵称为最大子矩阵。
例子:
0 -2 -7 0
9 2 -6 2
-4 1 -4 1
-1 8 0 -2
其最大子矩阵为:9 2
-4 1
-1 8
其元素总和为15。-
输入
- 第一行输入一个整数n(0<n<=100),表示有n组测试数据;
每组测试数据:
第一行有两个的整数r,c(0<r,c<=100),r、c分别代表矩阵的行和列;
随后有r行,每行有c个整数;
输出 - 输出矩阵的最大子矩阵的元素之和。 样例输入
-
1 4 4 0 -2 -7 0 9 2 -6 2 -4 1 -4 1 -1 8 0 -2
样例输出 -
15
- 第一行输入一个整数n(0<n<=100),表示有n组测试数据;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner=new Scanner(System.in);
int times=scanner.nextInt();
while(times--!=0)
{
int row=scanner.nextInt();
int column=scanner.nextInt();
int arr[][]=new int[row+1][column];
for(int i=1;i<=row;i++)
{
for(int j=0;j<column;j++)
{
arr[i][j]=scanner.nextInt();
arr[i][j]+=arr[i-1][j];
}
}
int max=arr[1][0];
//存放整体的最大值,初值为矩阵第一个数
for(int i=0;i<row;i++)
{
for(int j=i+1;j<=row;j++)
{
int temp=0;
//存放每个小矩阵的最大值
for(int k=0;k<column;k++)
{
temp=temp>=0?temp:0;
temp+=arr[j][k]-arr[i][k];
max=max>temp?max:temp;
}
}
}
System.out.println(max);
}
}
}