Maximum Subarray Sum

http://www.lintcode.com/en/problem/maximum-subarray/

Question

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

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.

Analysis

DP和Greedy均可进行求解,不过还是更推荐使用DP,因为Greedy很多情况下都是不正确的。

Dynamic Programming:

maxSubArray(A, i) = maxSubArray(A, i - 1) > 0 ? maxSubArray(A, i - 1) : 0 + A[i];

Kadane's Algorithm

Solution

Brute-force Compare all subarray sum (119 ms 2.49% AC)

// Compare all subarray sum: O(n^2)
class Solution {
    public int maxSubArray(int[] nums) {
        int maxSum = Integer.MIN_VALUE;
        int sum;
        for (int i = 0; i < nums.length; i++) {
            sum = 0;
            for (int j = i; j < nums.length; j++) {
                sum += nums[j];
                maxSum = Math.max(sum, maxSum);
            }
        }
        return maxSum;
    }
}

Improvement O(n) (7ms 93.68% AC)

Dynamic Programming

Greedy Algorithm

Prefix Sum

Kadane's Alogrithm

Maximum Subarray II

Maximum Subarray III

Maximum Subarray IV

Reference

Last updated

Was this helpful?