穷举法是最容易想出的解法,反正就是把所有能举出的子序列都算一遍和,找出最大的一个就是,复杂度O(N*N)

 

      对于分治法来说,是比较简单的,对半分成求解左右两个序列的最大子序列,不过终止条件应该是什么呢?我的想法是到只剩一个元素的序列的话,直接返回这个元素就是了,可书上都是如果大于0,返回此元素,若小于0,则返回0,这里想不明白。最难的部分应该是,要考虑跨左右两个子序列的情况。

None.gifint MaxSubSeqSum(int a[],int left,int right)
ExpandedBlockStart.gifContractedBlock.gifdot.gif{
InBlock.gif    if(left==right)
ExpandedSubBlockStart.gifContractedSubBlock.gif    dot.gif{
InBlock.gif        return a[left];
ExpandedSubBlockEnd.gif    }
InBlock.gif    int mid = (left+right)/2;
InBlock.gif    int i,lSum=0,rSum=0,tmpLMax=0,tmpRMax=0;
InBlock.gif    for(i=mid;i>=left;--i)
ExpandedSubBlockStart.gifContractedSubBlock.gif    dot.gif{
InBlock.gif        lSum+=a[i];
InBlock.gif        if(lSum>tmpLMax)
ExpandedSubBlockStart.gifContractedSubBlock.gif        dot.gif{
InBlock.gif            tmpLMax = lSum;
ExpandedSubBlockEnd.gif        }
ExpandedSubBlockEnd.gif    }
InBlock.gif    for(i=mid+1;i<=right;++i)
ExpandedSubBlockStart.gifContractedSubBlock.gif    dot.gif{
InBlock.gif        rSum+=a[i];
InBlock.gif        if(rSum>tmpRMax)
ExpandedSubBlockStart.gifContractedSubBlock.gif        dot.gif{
InBlock.gif            tmpRMax = rSum;
ExpandedSubBlockEnd.gif        }
ExpandedSubBlockEnd.gif    }
InBlock.gif    int overMax = tmpLMax+tmpRMax;
InBlock.gif    int lMax = MaxSubSeqSum(a,left,mid);
InBlock.gif    int rMax = MaxSubSeqSum(a,mid+1,right);
InBlock.gif    return  max(max(overMax,lMax),rMax);
ExpandedBlockEnd.gif}
None.gif

      动态规划的方法就太巧妙了,巧就巧在它扫描时会跟踪序列上升还是下降的趋势,从而把前面不适合的部分都给抛弃了,就一路走一路抛,并且同时把合适的记忆住了。

None.gifint MaxSubSeqSum2(int a[],int len)
ExpandedBlockStart.gifContractedBlock.gifdot.gif{
InBlock.gif    int tmpSum=0,maxSum = 0;
InBlock.gif    for(int i=0;i<len;++i)
ExpandedSubBlockStart.gifContractedSubBlock.gif    dot.gif{
InBlock.gif        tmpSum+=a[i];
InBlock.gif        if(tmpSum>maxSum)
ExpandedSubBlockStart.gifContractedSubBlock.gif        dot.gif{
InBlock.gif           maxSum = tmpSum;
ExpandedSubBlockEnd.gif        }
InBlock.gif        else if(tmpSum<0)
ExpandedSubBlockStart.gifContractedSubBlock.gif        dot.gif{
InBlock.gif             tmpSum=0;
ExpandedSubBlockEnd.gif        }
ExpandedSubBlockEnd.gif    }
InBlock.gif    return maxSum;
InBlock.gif    
ExpandedBlockEnd.gif}
None.gif
None.gif