[LeetCode] Maximum Subarray

Problem

Find the contiguous subarray within an array (containing at least one number) which has the largest sum.

Example

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.

Solution

class Solution {
    public int maxSubArray(int[] nums) {
        if (nums == null || nums.length == 0) return 0;
        int max = nums[0], sum = max;
        for (int i = 1; i < nums.length; i++) {
            if (sum < 0) {
                sum = nums[i];
            } else {
                sum += nums[i];
            }
            max = Math.max(max, sum);
        }
        return max;
    }
}
DP
class Solution {
    public int maxSubArray(int[] nums) {
        int sum = nums[0], n = nums.length;
        int[] dp = new int[n];
        dp[0] = sum;
        for (int i = 1; i < n; i++) {
            if (sum < 0) sum = nums[i];
            else sum += nums[i];
            dp[i] = Math.max(dp[i-1], sum);
        }
        return dp[n-1];
    }
}

你可能感兴趣的:(divide-conquer,LintCode,java,数组)