Given an integer array nums, find the contiguous subarray (containing at least one number) which has the largest sum and return its sum.
Example:
Input: [-2,1,-3,4,-1,2,1,-5,4],
Output: 6
Explanation: [4,-1,2,1] has the largest sum = 6.
Follow up:
If you have figured out the O(n) solution, try coding another solution using the divide and conquer approach, which is more subtle.
functionLSS(list) {constlen=list.length;let max = list[0];let min =0;let sum =0;for (let i =0; i < len; i++) { sum += list[i];if (sum - min > max) max = sum - min;if (sum < min) { min = sum; } }return max;}
解法四 - 分治法
Java code
classMaximumSubarrayDivideConquer {publicintmaxSubArrayDividConquer(int[] nums) {if (nums ==null||nums.length==0) return0;returnhelper(nums,0,nums.length-1); }privateinthelper(int[] nums,int l,int r) {if (l > r) returnInteger.MIN_VALUE;int mid = (l + r) >>>1;int left =helper(nums, l, mid -1);int right =helper(nums, mid +1, r);int leftMaxSum =0;int sum =0;// left surfix maxSum start from index mid - 1 to lfor (int i = mid -1; i >= l; i--) { sum += nums[i]; leftMaxSum =Math.max(leftMaxSum, sum); }int rightMaxSum =0; sum =0;// right prefix maxSum start from index mid + 1 to rfor (int i = mid +1; i <= r; i++) { sum += nums[i]; rightMaxSum =Math.max(sum, rightMaxSum); }// max(left, right, crossSum)returnMath.max(leftMaxSum + rightMaxSum + nums[mid],Math.max(left, right)); }}
Python3 code
import sysclassSolution:defmaxSubArray(self,nums: List[int]) ->int:return self.helper(nums, 0, len(nums) -1)defhelper(self,nums,l,r):if l > r:return-sys.maxsize mid = (l + r) //2 left = self.helper(nums, l, mid -1) right = self.helper(nums, mid +1, r) left_suffix_max_sum = right_prefix_max_sum =0sum=0for i inreversed(range(l, mid)):sum+= nums[i] left_suffix_max_sum =max(left_suffix_max_sum, sum)sum=0for i inrange(mid +1, r +1):sum+= nums[i] right_prefix_max_sum =max(right_prefix_max_sum, sum) cross_max_sum = left_suffix_max_sum + right_prefix_max_sum + nums[mid]returnmax(cross_max_sum, left, right)