首页 > 其他 > 详细

53. Maximum Subarray

时间:2018-01-18 23:32:41      阅读:190      评论: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.

翻译:找最大连续子数组(至少一个数)

大神答案(自己木有做出来)

public static int maxSubArray(int[] A) {
    int maxSoFar=A[0], maxEndingHere=A[0];//maxSoFar用来记录目前为止找到的最大子数组;maxEndingHere用来表示当前连续累加的和
    for (int i=1;i<A.length;++i){
    	maxEndingHere= Math.max(maxEndingHere+A[i],A[i]);//对数组中每个数,判断该数自己大,还是和之前的累加和加起来大,选最大的一个
    	maxSoFar=Math.max(maxSoFar, maxEndingHere);//maxSoFar是历史中出现过的最大值;maxEndingHere是目前的值,两者选最大的一个	
    }
    return maxSoFar;
}


53. Maximum Subarray

原文:https://www.cnblogs.com/mafang/p/8313403.html

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