采用递归求数组里面求最大子序列的算法(手绘图解)

本文改编自我在知乎的回答。http://t.cn/RqPi9FO

先上代码。

private static int maxSumRec( int [ ] a, int left, int right )


    {
        int maxLeftBorderSum = 0, maxRightBorderSum = 0;
        int leftBorderSum = 0, rightBorderSum = 0;
        int center = ( left + right ) / 2;

        if( left == right )  // Base case
            return a[ left ] > 0 ? a[ left ] : 0;

        int maxLeftSum  = maxSumRec( a, left, center );
        int maxRightSum = maxSumRec( a, center + 1, right );

        for( int i = center; i >= left; i-- )
        {
            leftBorderSum += a[ i ];
            if( leftBorderSum > maxLeftBorderSum )
                maxLeftBorderSum = leftBorderSum;
        }

        for( int i = center + 1; i <= right; i++ )
        {
            rightBorderSum += a[ i ];
            if( rightBorderSum > maxRightBorderSum )
                maxRightBorderSum = rightBorderSum;
        }

        return max3( maxLeftSum, maxRightSum,
                     maxLeftBorderSum + maxRightBorderSum );
    }

private static int max3( int a, int b, int c )
    {
        return a > b ? a > c ? a : c : b > c ? b : c;
    }

public static int maxSubSum3( int [ ] a )
    {
        return a.length > 0 ? maxSumRec( a, 0, a.length - 1 ) : 0;
    }




首先要理解递归,图转自知乎上递归的一个答案中。

当递归找到基准,可以返回时,它会回到函数调用的位置,继续执行下方的语句。

关于这道题,我手写了一个过程,希望有所帮助。顺序是A(A1,A2,A3,A4)B,C,D。

对于B同样有(B1,B2,B3,B4)

这个算法是四步,求左,求右,求中间往两边(一定理解是从中间往两边,因为是一个贯通中点的子序列),求三者中最大的。


时间复杂度是NlogN。

posted on 2016-03-25 08:41  雪峰00  阅读(256)  评论(0)    收藏  举报

导航