2014年2月10日星期一

LeetCoder - 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.
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.

public class Solution {
    public int maxSubArray(int[] A) {
        if(A==null || A.length==0) {
            return 0;
        }
        int[] max = new int[A.length];
        max[0] = A[0];
        int m = A[0];
        for(int i=1;i<A.length;i++) {
            int a = A[i];
            max[i] = Math.max(a, max[i-1]+a);
            if(max[i]>m) {
                m = max[i];
            }
        }
        return m;
    }
}


public class Solution {
    public int maxSubArray(int[] A) {
        if(A==null || A.length==0) {
            return 0;
        }
        int max = A[0];
        int curSum = A[0];
        for(int i=1;i<A.length;i++) {
            if(curSum<0) {
                curSum = A[i];
            } else {
                curSum += A[i];
            }
            max = Math.max(curSum, max);
        }
        return max;
    }
}

没有评论:

发表评论