[LeetCode] Maximum Subarray
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
.
Click to show more practice.
Solution:
Find out the sum of the continuous and largest sub-arrays. There are two ways to do this: Dynamic Planning and division and control.
1. Dynamic Planning. The dynamic planning method can be considered for the maximization problem. D [I] indicates the maximum value of the subarray nums [k, I], where k> = 0 and k
D [I] = nums [I], I = 0 or d [I-1] <0d [I] = nums [I] + d [I-1], others
Then return the maximum value of the d [] array. The spatial complexity of this method is O (n), which can be optimized to O (1. The time complexity is O (n)
class Solution {public: int maxSubArray(vector
& nums) { int len = nums.size(); if(len<1){ return 0; } int d[len]; d[0]=nums[0]; int maxSum=nums[0]; for(int i=1; i
0){ d[i]=nums[i]+d[i-1]; }else{ d[i]=nums[i]; } maxSum = max(d[i], maxSum); } return maxSum; }};
2. Divide and conquer law. This method is very clever. For an array nums [left, right], nums [mid] is its intermediate element. The distribution of the maximum sub-array is nothing more than three situations:
(1) The maximum sub-array is before the mid
(2) The maximum sub-array is behind the mid
(3) The maximum sub-array spans the mid
For (1) (2), we can use recursion to obtain the maximum sum. For (3), we use mid to extend to both sides. Then, the maximum value of the three conditions is returned.
The space complexity is O (1), and the time complexity is O (n)
class Solution {public: int maxSubArray(vector
& nums) { return maxSub(nums, 0, nums.size() - 1); } int maxSub(vector
& nums, int left, int right){ if(left>right){ return INT_MIN; } int mid = (left + right) / 2; int lMax = maxSub(nums, left, mid - 1); int rMax = maxSub(nums, mid + 1, right); int sum = 0; int lMaxSub = 0; for(int i=mid - 1; i>=left; i--){ sum += nums[i]; lMaxSub = max(sum, lMaxSub); } int rMaxSub = 0; sum = 0; for(int i=mid + 1; i<=right; i++){ sum += nums[i]; rMaxSub = max(sum, rMaxSub); } return max(max(lMax, rMax), lMaxSub + rMaxSub + nums[mid]); }};