首页 > 其他 > 详细

最大子数组

时间:2014-02-27 01:13:56      阅读:387      评论:0      收藏: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<A.length;i++)
		{
	    	if(A[i]>tmp+A[i])
			{
			    tmp = A[i];
			}
			else
			{
				tmp+=A[i];
			}
			if(sum<tmp)
				sum = tmp;
		}
		return sum;
	}




最大子数组,布布扣,bubuko.com

最大子数组

原文:http://blog.csdn.net/cow__sky/article/details/19963235

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!