【Leetcode】Maximum Subarray

题目链接:https://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.

If you have figured out the O(n) solution, try coding another solution using the divide and conquer approach, which is more subtle.

思路:

用sum维护一个当前元素之前大于0的连续子串,因为只要大于0,它就有跟下一个元素连接的价值。

用max表示到当前元素为止的最大连续和。


算法:

	public int maxSubArray(int[] nums) {
		int max = nums[0];
		int sum = nums[0];
		for (int i = 1; i < nums.length; i++) {
			if (sum < 0)
				sum = 0;// 如果前面元素和小于0,与其加个负数,不如从清零从当前元素开始
			sum += nums[i];
			max = Math.max(max, sum);
		}
		return max;
	}


你可能感兴趣的:(【Leetcode】Maximum Subarray)