码迷,mamicode.com
首页 > 其他好文 > 详细

53. Maximum Subarray

时间:2018-01-19 00:24:53      阅读:185      评论:0      收藏:0      [点我收藏+]

标签:连续   记录   array   body   ast   UI   find   within   数组   

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

标签:连续   记录   array   body   ast   UI   find   within   数组   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!