[leetcode]Maximum Subarray

新博文地址:[leetcode]Maximum Subarray

http://oj.leetcode.com/problems/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.

 很经典的DP问题,不多说,一个需要注意的地方:

当全部为负数时,只能去最小的负数,而不是返回0。复杂度O(n)。

分治法:复杂度O(n^2)。见新博文

 

 public int maxSubArray(int[] A) {
		if(A == null || A.length == 0){
			return 0;
		}
		int max = Integer.MIN_VALUE;
		int sum = 0;
		for (int i = 0; i < A.length; i++)	{
			if (sum <= 0){
				sum = 0;
			}
			sum += A[i];
			if (sum > max){
				max = sum;
			}
		}
		return max;
	}

 

你可能感兴趣的:(LeetCode)