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.

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.

分析:这道题可以在剑指Offer上面查到,面试题31连续子数组的最大和。上面写的很详细,我也是用的上面说的方法做到的。

class Solution {
public:
    int maxSubArray(int A[], int n) {
        if(n<=0)
        {
            return 0;
        }
        int nCurSum=0;
        int maxSum=0x80000000;
        for(int i=0;i<n;++i)
        {
            if(nCurSum<=0)
                nCurSum=A[i];
            else
                nCurSum+=A[i];
            if(nCurSum>maxSum)
                maxSum=nCurSum;
        }
        return maxSum;
    }
};
原文地址:https://www.cnblogs.com/awy-blog/p/3590562.html