最大子数组

2014-11-24 09:43:21 · 作者: · 浏览: 0

题目原型:

Find the contiguous subarray within an array (containing at least one number) which has the largest sum.

For example, given the array [ 2,1, 3,4, 1,2,1, 5,4],
the contiguous subarray [4, 1,2,1] has the largest sum = 6.

click to show more practice.

More practice:

If you have figured out the O(n) solution, try coding another solution using the divide and conquer approach, which is more subtle.

基本思路:

令数组为A,从前往后累加得tmp,sum为最大的累加和。

1、如果A[i]>A[i]+tmp,表示,加了还不如不加,那么初始化tmp,令tmp=A[i]。若tmp>sum,则更新sum 。

2、否则,累加tmp,同时注意更新sum。

	public int maxSubArray(int[] A)
	{
		if(A.length==0||A==null)
			return 0;
		int sum = A[0];
		int tmp = A[0];
		for(int i = 1;i
  
   tmp+A[i])
			{
			    tmp = A[i];
			}
			else
			{
				tmp+=A[i];
			}
			if(sum