package day; /** * 两个子数组的最大和 * 1.先逆序从右忘左算出以每一个index位开始到右的累加和记载在h[]中, * 在正序遍历最大的累加和,遍历的过程中前后最大值累加,记载最大值 * @author Administrator * */ public class Demo1 { public int method(int[] array){ int arraylength = array.length; int[] h = new int[arraylength]; h[arraylength - 1] = array[arraylength - 1]; int cur = array[arraylength - 1]; for(int i = arraylength - 2;i >=0;i --){ cur = cur < 0 ? 0 : cur; cur= array[i] + cur; h[i] = Math.max(cur, h[i + 1]); } cur = array[0]; int lmax = array[0]; int max = array[0] + h[1]; for(int i = 1;i < array.length - 1;i ++){ cur = cur < 0 ? 0 : cur; cur = cur + array[i]; lmax = Math.max(cur, lmax); max = Math.max((lmax + h[i + 1]), max); } return max; } public static void main(String[] args) { int[] array = {1,-5,7,-4,6,-9,3,6,-7}; System.out.println(new Demo1().method(array)); } }