子数组的最大累加和

题目:

给定一个数组arr,返回子数组的最大累加和。例如:arr[1,-2,3,5,-2,6,-1],所有的子数组中,[3,5,-2,6]可以累加出最大值为12,所以返回12.

分析:

1.如果数组中没有正数,产生的最大和就是数组中的最大值。

2.如果arr中有正数,从左到右遍历arr,用变量cur记录每一步的累加和,遍历到正数cur增加,遍历到负数cur减少,当cur<0时,说明累加到当前数出现小于0,那么累加这一部分不能作为产生最大累加和

的子数组左边部分,此时令cur=0,表示重新从下一个数开始累加。当cur>=0时,每一次累加都可能是最大累加和,所以用另一个变量max记录cur出现的最大值。

package demo2;

public class Main {

	public static void main(String[] args) {
		int array[] = {6,-3,-2,7,-15,1,2,2};
		
		int sum = FindGreatestSumOfSubArray(array);
		
		System.out.println(sum);
	}
	
	
	
	
	
	
	
	
	 public static int FindGreatestSumOfSubArray(int[] array) {
	 
		 if (array == null || array.length == 0) {
			 return 0;
		 }
		 int max = Integer.MIN_VALUE;
		 int cur = 0;
		 for (int i=0;i<array.length;i++) {
			 cur += array[i];
			 max = Math.max(max, cur);
			 cur = cur<0?0:cur;
		 }	 
		 return max;
		 
	 }
	
}

 

posted on 2017-03-25 13:30  airycode  阅读(1800)  评论(0)    收藏  举报

导航