LeetCode - Maximum Subarray

题注

这道题开始时候我绞尽脑汁也没想出来… 特别怀疑自己的智商,无奈去网上搜了搜,结果发现是一个经典的算法题,而且从提出到最后解决用了大概6年的时间,看来还真不是智商问题… 这些基础算法是王道,我们没有那么聪明,几乎不可能像大师那样自己设计高效的算法。那么,提高自己算法能力的方法就是掌握所有的基础算法,然后遇到问题进行规约。我想,这才是如我这种渣技术的人才能掌握的方法吧?说白了呢,就像计算机中用空间换时间的思路差不多啦~

题目

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.

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.

分析

作为一个博士生,虽然智商没那么高,但是刨根问底的精神还是有的。那么,先从Wikipedia开始搜索吧!在[1]中,很容易了解到这个问题的背景以及算法:

In computer science, the maximum subarray problem is the task of finding the contiguous subarray within a one-dimensional array of numbers (containing at least one positive number) which has the largest sum. For example, for the sequence of values [2, 1, -3, 4, -1, 2, 1, -5, 4]; the contiguous subarray with the largest sum is [4, -1, 2, 1], with sum 6.
The problem was first posed by Ulf Grenander of Brown University in 1977, as a simplified model for maximum likelihood estimation of patterns in digitized images. A linear time algorithm was found soon afterwards by Jay Kadane of Carnegie-Mellon University (Bentley 1984).

翻一翻原始论文,首先找到的是[2]。[2]中介绍了所有有关这一问题的算法,包括线性时间算法Kadane算法以及More Practice中提到的分治算法。不过,论文毕竟是论文,短时间全都消化也不太容易。我进一步找到了一个更好理解的材料[3],并把这个材料的关键部分翻译整理一下,以形成Kadane算法的分析与设计思路。

令$s_{j,k}$表示$A[j:k]$的和,我们定义

\[M_t = \max \{0, \max_{j \leq t} \{s_{j, t}\}\}\]

换句话说,$M_t$为0和$s_{j,k}$的最大值,其中我们限制$k = t$。这一定义意味着,如果$M_t > 0$,那么最大子序列的求和值以$A[t]$结尾;如果$M_t = 0$,那么我们可以忽略所有以$t$结尾的子数列。

注意到如果对于所有的$t = 1, 2, \cdots, n$,我们知道$M_t$的值,那么最大子数列问题的解为这些$M_t$的最大值。现在让我们考虑如何计算这些$M_t$的值。

我们要观察到一个关键的现象,对于$t \geq 2$,如果我们有一个以$A[t]$结尾的最大子数列,且其求和值为正数,那么最大子数列的解或者为$A[t:t]$,或者为以$A[t-1]$结尾的最大子数列加上$A[t]$。进一步,如果我们取以$A[t-1]$结尾的最大子数列,并加上$A[t]$,使得相加结果不为正数,那么$M_t = 0$,因为没有以$A[t]$为结尾的子数列的求和值为正数。换句话说,我们可以定义$M_0 = 0$为边界条件,利用下面的公式来对求所有的$t = 1, 2, \cdots, n$求$M_t$:

\[M_t = \max \{0, M_{t - 1} + A[t]\}\]

由此得到算法。


但是,如果给定的数组$A[1:n]$中所有的元素都为负数的话,这个算法的返回值将是0,但题目要求是最大子数列至少有一个元素,所以我们还需要改进这个算法。一种很自然的考虑就是先检查所有元素是否都为负数,如果都为负数,那么最大的那个负数就是解。这种算法的复杂度仍然为O(n)。不过,还有一种更加优化的算法,由[1]给出。最终我提交的答案就是[1]中修改版本后的java版本。


对于分治算法,[2]中也给出了详细的描述。在此我们给出Discuss中porker2008给出的解释和代码[4]:

Step1. Select the middle element of the array.So the maximum subarray may contain that middle element or not.

Step 2.1 If the maximum subarray does not contain the middle element, then we can apply the same algorithm to the the subarray to the left of the middle element and the subarray to the right of the middle element.

Step 2.2 If the maximum subarray does contain the middle element, then the result will be simply the maximum suffix subarray of the left subarray plus the maximum prefix subarray of the right subarray

Step 3 return the maximum of those three answer.

    public int maxSubArray(int[] A) {
        if(A.length == 0) {
    		return 0;
    	}
        return maxSubArrayHelperFunction(A, 0, A.length-1);
    }
    
    private int maxSubArrayHelperFunction(int A[], int left, int right) {
        if(right == left) {
        	return A[left];
        }
        int middle = (left+right)/2;
        int leftans = maxSubArrayHelperFunction(A, left, middle);
        int rightans = maxSubArrayHelperFunction(A, middle+1, right);
        int leftmax = A[middle];
        int rightmax = A[middle+1];
        int temp = 0;
        for (int i = middle; i >= left; i--) {
            temp += A[i];
            if(temp > leftmax) {
            	leftmax = temp;
            }
        }
        temp = 0;
        for(int i=middle+1;i<=right;i++) {
            temp += A[i];
            if(temp > rightmax) rightmax = temp;
        }
        return Math.max(Math.max(leftans, rightans),leftmax+rightmax);
    }

代码

public class Solution {
    public int maxSubArray(int[] A) {
        if (A.length == 0){
            return 0;
        }
        if (A.length == 1){
            //因为结果不能是一个空的队列,因此length = 1时返回A[0]
            return A[0];
        }
        int max_ending_here = A[0];
        int max_so_far = A[0];
        for (int i=1; i<A.length; i++){
            int x = A[i];
            max_ending_here = Math.max(x, max_ending_here + x);
            max_so_far = Math.max(max_so_far, max_ending_here);
        }
        return max_so_far;
    }
}

参考文献

[1] Maximum subarray problem. Available at: http://en.wikipedia.org/wiki/Maximum_subarray_problem.

[2] Bentley Jon, "Programming pearls: algorithm design techniques", Communications of the ACM. 27(9): 865–873, 1984.

[3] A Case Study in Algorithm Analysis. Available at: http://www.ics.uci.edu/~goodrich/teach/cs161/notes/MaxSubarray.pdf.

[4] how to solve "Maximum Subarray" by using the divide and conquer approach? Available at: http://oj.leetcode.com/discuss/694/how-solve-maximum-subarray-using-divide-and-conquer-approach

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值