问题描述
题目是全英的,大意就是输入一个 正整数N和一个NxN的矩阵,然后输出该矩阵的最大子矩阵的值;例如输入矩阵:
0 -2 -7 0
9 2 -6 2
-4 1 -4 1
-1 8 0 -2
你应该输出:
15
因为矩阵的最大子矩阵为:
9 2
-4 1
-1 8
该子矩阵的和为15
数据范围:1<=N<=100;矩阵中的元素值取值范围为 [ -127,127]
样例输入
4
0 -2 -7 0
9 2 -6 2
-4 1 -4 1
-1 8 0 -2
样例输出
15
java题解:
import java.util.Arrays;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
//int m = sc.nextInt();
int[][] s = new int[n][n];
int max=-10010;
for(int i=0;i<n;i++)
for(int j=0;j<n;j++)
s[i][j] = sc.nextInt();
int[] temp; // 将NxN的矩阵一行一行分层开来,每一层叠加上一层的值,然后计算该层的最大连续子序列
for(int i=0;i<n;i++){ // 从第一行开始遍历,该循环循环一次之后可以得出包含第i行的矩阵的最大子矩阵值
temp = new int[n]; // 每次大循环都初始化一次
for(int j=i;j<n;j++){ // 从第i行开始遍历,计算第i行到n-1行的最大子矩阵值
for(int k=0;k<n;k++) // 计算第i行到第j行的矩阵的矩阵值
temp[k]+=s[j][k]; // 叠加第i行到第j行的值,每一层都是一个序列
max = max(max,findMax(temp)); // fingMax函数用于查找最大连续子序列
}
}
System.out.println(max);
}
private static int findMax(int[] t) { // 查找序列t中的最大连续子序列
int max=-10010;
int temp=0;
for(int i=0;i<t.length;i++){
temp+=t[i];
if(temp>max)
max=temp;
if(temp<0)
temp=0;
}
return max;
}
private static int max(int a, int b) {
if(a<b)
return b;
return a;
}
}