package com.hzins.suanfa; public class MaxSum { public static int function(int[] array) { int cur = array[0]; int max = array[0]; for (int i = 1; i < array.length; i++) { cur = cur < 0 ? 0 : cur; cur += array[i]; max = Math.max(max, cur); } return max; } /** * O(n^3) * @param array * @return */ public static int maxMatrixSum(int[][] array) { int max = 0; int[] sumArray = null; int sumArrayLength = array[0].length; //前两个for作用 第一行到第五行 第二行到第五行 。。。。。 从上到下累加成一维数组 for (int i = 0; i < array.length; i++) { sumArray = new int[sumArrayLength]; for (int j = i; j < array.length; j++) { int cur = 0; //开始变成子数组中最大累加和问题 每一个这个问题需要一个全新的cur for (int k = 0; k < sumArrayLength; k++) { cur = cur < 0 ? 0 : cur; sumArray[k] += array[j][k]; cur += sumArray[k]; max = Math.max(cur, max); } } } return max; } public static void main(String[] args) { int[][] a = new int[3][5]; for(int i = 0;i < a.length;i ++){ a[i][0] = 3; a[i][1] = -4; a[i][2] = 7; a[i][3] = -4; a[i][4] = 2; } for(int i = 0;i< a.length;i++){ for (int j = 0;j < a[0].length;j ++){ System.out.print(a[i][j] + " "); } System.out.println(); } System.out.println(maxMatrixSum(a)); } }