Maximum Subarray - Dynamic Programming Way

Quesiton

from lintcode

Given an array of integers, find a contiguous subarray which has the largest sum.

Notice
The subarray should contain at least one number.

Example
Given the array [−2,2,−3,4,−1,2,1,−5,3], the contiguous subarray [4,−1,2,1] has the largest sum = 6.

Idea

One key note: Subarray = continuous elements. As you roll over each element at position X with a DP sum function, you might miss the correct answer whose elements are not adjacent to the position X. You need to remember the result with another DP function. See code below.

public class Solution {
    /**
     * @param nums: A list of integers
     * @return: A integer indicate the sum of max subarray
     */
    public int maxSubArray(int[] nums) {
        if (nums.length == 0) return 0;
        
        int n = nums.length;
        int[] global = new int[2];
        int[] local = new int[2];
        
        // global[x] means the max sum from certain i-index to certain j-index, where i <= x and j <=x, x-index element may not be included
        global[0] = nums[0];

        // local[x] means the max sum from certain i-index to x-index, x-index element is always included
        local[0] = nums[0];
        
        for(int i = 1; i < n; i++) {
            local[i % 2] = Math.max(nums[i], local[(i - 1) % 2] + nums[i]);
            global[i % 2] = Math.max(local[i % 2], global[(i - 1) % 2]);
        }
        
        return global[(n - 1) % 2];
    }
}

你可能感兴趣的:(Maximum Subarray - Dynamic Programming Way)