package base; //最大子序列和,包括全负数情况。 思想是依次遍历数组,如何本次的和大于上次的和 则本次大,并且如果本次和为0 则 //开始指针移动到i++位置 public class MaxSubSeq { public static void main(String[] args) { MaxSubSeq mss = new MaxSubSeq(); System.out.println("The max is = " + mss.getMaxSubSeq(new int[]{-1,-3,-21,-3,-5,-2})); } private int getMaxSubSeq(int[] array){ int arraySize = array.length; int start = 0; //开始指针 int finish = 0; //结束指针 int sum = 0; //最大累加和 int max = 0; //上一次的累加和 int _max = Integer.MIN_VALUE; //系统最小负值(如果和值为负则为最大值) int _maxI = 0; //全负值情况坐标 for(int i=0;i<arraySize;i++){ sum += array[i]; if(_max < array[i]){ _max = array[i]; _maxI = i; } if(sum <= 0){ start = i+1; sum = 0; } if(sum > max){ max = sum; finish = i; } } if(_max < 0){ System.out.println("The start is = " + _maxI + " and The end is = " + _maxI); return _max; } System.out.println("The start is = " + start + " and The end is = " + finish); return max; } }