题目描述
已知矩阵的大小定义为矩阵中所有元素的和。给定一个矩阵,你的任务是找到最大的非空(大小至少是1 * 1)子矩阵。 比如,如下4 * 4的矩阵 0 -2 -7 0 9 2 -6 2 -4 1 -4 1 -1 8 0 -2 的最大子矩阵是 9 2 -4 1 -1 8 这个子矩阵的大小是15。
输入描述:
输入是一个N * N的矩阵。输入的第一行给出N (0 < N <= 100)。 再后面的若干行中,依次(首先从左到右给出第一行的N个整数,再从左到右给出第二行的N个整数……)给出矩阵中的N2个整数,整数之间由空白字符分隔(空格或者空行)。 已知矩阵中整数的范围都在[-127, 127]。
输出描述:
测试数据可能有多组,对于每组测试数据,输出最大子矩阵的大小。
链接:https://www.nowcoder.com/questionTerminal/a5a0b05f0505406ca837a3a76a5419b3 来源:牛客网 import java.util.Scanner; public class Main{ public static int Sum(int[] arr){ int res = Integer.MIN_VALUE; int cur = 0; for(int i = 0;i < arr.length;i++){ cur += arr[i]; res = Math.max(res,cur); if(cur < 0) cur = 0; } return res; } public static int MaxRect(int[][] arr){ int max = Integer.MIN_VALUE; int m = arr.length; int n = arr[0].length; for(int i = 0 ;i < m ;i++){ int[] temp = new int[n]; for(int j = i;j < m;j++){ for(int k = 0;k < n;k++){ temp[k] += arr[j][k]; } max = Math.max(max,Sum(temp)); } } return max; } public static void main(String args[]) { Scanner sc = new Scanner(System.in); int N = sc.nextInt(); int[][] rec = new int[N][N]; for(int i = 0 ;i < N;i++) for(int j = 0;j < N;j++) rec[i][j] = sc.nextInt(); System.out.println(MaxRect(rec)); } }