LeetCode 100 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.

click to show more practice.

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.

分析:

因为这里不要求返回数组下标,可以通过一趟遍历来把所有元素相加,当和小于0的时候,舍弃之前所有。

这里是一个O(n)的解法。

public class Solution {
    public int maxSubArray(int[] A) {
        int sum = 0;
        int maxSum = Integer.MIN_VALUE;
        for(int i=0; i<A.length; i++){
            sum += A[i];
            maxSum = Math.max(maxSum, sum);
            if(sum < 0)
                sum=0;
        }
        return maxSum;
    }
}


你可能感兴趣的:(LeetCode,maximum,Subarray)