题解 | #最大子矩阵#
最大子矩阵
https://www.nowcoder.com/practice/a5a0b05f0505406ca837a3a76a5419b3
如果能装换为一维数组求最大的连续子序列就好了。
把二维数组压扁,dp数组每一行代表以上列的和,然后枚举n行到0行(n行减上面的行就是这两行之间的行)之间可能的最大连续子序列即可。
import java.util.Scanner; // 注意类名必须为 Main, 不要有任何 package xxx 信息 public class Main { static int res = Integer.MIN_VALUE; public static void main(String[] args) { Scanner in = new Scanner(System.in); int n = in.nextInt(); int[][] arr = new int[n][n]; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { arr[i][j] = in.nextInt(); } } if (n==1){ System.out.println(arr[0][0]); return; } int[][] dp = new int[n][n]; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { if (i == 0) { dp[i][j] = arr[i][j]; } else { dp[i][j] = arr[i][j] + dp[i - 1][j]; } } } int[] x = new int[n]; for (int i = 0; i < n; i++) { for (int j = 0; j <= i; j++) { if (i == j) { x = dp[i]; dfs(x); } else if (j < i) { x = fun(dp[i], dp[j]); dfs(x); } } } System.out.println(res); } private static void dfs(int[] x) { int[] dp = new int[x.length]; dp[0] = x[0]; res = Math.max(dp[0], res); for (int i = 1; i < dp.length; i++) { dp[i] = Math.max(dp[i - 1] + x[i], x[i]); res = Math.max(dp[i], res); } } private static int[] fun(int[] ints, int[] ints1) { int[] ints2 = new int[ints.length]; for (int i = 0; i < ints2.length; i++) { ints2[i] = ints[i] - ints1[i]; } return ints2; } }