53. Maximum Subarray

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;
}


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