题目:
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.
If you have figured out the O(n) solution, try coding another solution using the divide and conquer approach, which is more subtle.
简单做法:全局sumMax记录全局最大,局部sum,当sum小于零时令sum = 0。
复杂做法:Divide and Conquer。左最大,右最大,左右+mid 连起最大。
C++版:
class Solution { public: int maxSubArray(vector<int>& nums) { return maxSub(nums, 0, nums.size() - 1); } int maxSub(vector<int>& nums, int start, int end) { if(start > end) return INT_MIN; int mid = (start + end) / 2; int leftMax = maxSub(nums, start, mid - 1); int rightMax = maxSub(nums, mid + 1, end); int sum = 0, lmax = 0, rmax = 0; for(int i = mid - 1; i >= start; i--) { sum += nums[i]; if(sum > lmax) lmax = sum; } sum = 0; for(int i = mid + 1; i <= end; i++) { sum += nums[i]; if(sum > rmax) rmax = sum; } return max(max(leftMax, rightMax), lmax + rmax + nums[mid]); } };
public class Solution { public int maxSubArray(int[] nums) { return maxSub(nums, 0, nums.length - 1); } public int maxSub(int[] nums, int start, int end) { if(start > end) return Integer.MIN_VALUE; int mid = (start + end) / 2; int leftMax = maxSub(nums, start, mid - 1); int rightMax = maxSub(nums, mid + 1, end); int sum = 0, lmax = 0, rmax = 0; for(int i = mid - 1; i >= start; i--) { sum += nums[i]; if(sum > lmax) lmax = sum; } sum = 0; for(int i = mid + 1; i <= end; i++) { sum += nums[i]; if(sum > rmax) rmax = sum; } return Math.max(Math.max(leftMax, rightMax), lmax + nums[mid] + rmax); } }
class Solution: # @param {integer[]} nums # @return {integer} def maxSubArray(self, nums): maxSum, sum, i = -sys.maxint, 0, 0 while i < len(nums): sum += nums[i] if sum > maxSum: maxSum = sum if sum < 0: sum = 0 i += 1 return maxSum