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.

最大子序列

class Solution {
public:
    int maxSubArray(int A[], int n) 
    {
        int sum = INT_MIN;
        int temp = 0;
        for(int i=0;i<n;i++)
        {
            if(temp>0)
                temp += A[i];
            else
                temp = A[i];
                
            if(temp>sum)
                sum = temp;
        }
        return sum;
    }
};

含义:从元素i开始,到元素j为止的所有的元素构成的子段有多个,这些子段中的子段和最大的那个。
那么:
   如果:b[j-1]>0, 那么b[j]=b[j-1]+a[j]    

   如果:b[j-1]<=0,那么b[j]=a[j]

这样,显然,我们要求的最大子段和,是b[j]数组中最大的那个元素。


posted @ 2014-03-15 20:20  海滨银枪小霸王  阅读(104)  评论(0编辑  收藏  举报