`
huntfor
  • 浏览: 195198 次
  • 性别: Icon_minigender_1
  • 来自: 杭州
社区版块
存档分类
最新评论

[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;
	}

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics