Maximum Subarray

Problem

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.

Solution

Typical DP Solution: O(n) time

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

Analysis

We need to find out the max sum of sub-array
Because the problem requires contiguous sub-array, it makes this problem become DP
The initial state is dp[0] = nums[0]
dp[i] depends on whether [dp] > 0, if so, dp[i] = dp[i - 1] + nums[i]
Otherwise we set dp[i] = nums[i] because there is no need to add previous number
Notice that we need to find out the max sum, so we have max and compare it with dp[i] in the loop
At the end, we return max not dp[len - 1]!

results matching ""

    No results matching ""