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

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

猜你喜欢

转载自likesky3.iteye.com/blog/2202575