Maximum subarray:https://leetcode.com/problems/maximum-subarray/
Find the contiguous subarray within an array (containing at least one number) which have 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.
More Practice:
If you had figured out of the O (n) solution, try coding another solution using the divide and conquer approach, which is mor E subtle.
Contiguous continuous
Analytical:
1. Dynamic Programming method
When traversing an array element from the beginning, there are several options for an integer in the array.
Two kinds: subarray before joining; a new subarray of his own. Inthat case, there are two situations:
-When the sum of previous subarray is greater than 0 , we think it contributes to subsequent results, in which case we opt to join the Subarray before
-When the sum of the previous subarray is less than or equal to 0 , we think it has no contribution to the subsequent results, in which case we choose to start with the current number and another Subarray
Set the state F (j) to denote the nums[j of the largest continuous subsequence at the end of the sequence, then the state transition equation is as follows:
F (j) = Max{f (j) +nums[j], Nums[j]}, where 1<=j<=n
target = Max{f (j)}, where 1<=j<=n
class Solution {public: // 时间复杂度 O(n) int maxSubArray(vector<int>& nums) { int result = INT_MIN; int0; for (int0; i < nums.size(); i++) { sum = max(sum+nums[i], nums[i]); result = max(result, sum); } return result; }};
2. Divide and conquer law
The maximum number of contiguous sub-sequences may exist in three intervals:
1. Completely in Nums[left, Mid-1]
2. Completely in nums[mid+1, right]
3. Include Nums[mid], then extend to left and right
Finally, the left sub-sequence, right sub-sequence and intermediate sequence are compared, and the maximal and.
classSolution { Public://Time complexity O (NLOGN) intMaxsubarray ( vector<int>& Nums) {returnDivide (Nums,0, Nums.size ()-1); }Private:intDivide vector<int>& Nums,intLeftintright) {if(left = right)returnNums[left];if(left+1= = right)returnMax (Nums[left]+nums[right], Max (Nums[left], nums[right]));intMid = (left+right)/2;intLeft_max = Divide (Nums, left, mid-1);intRight_max = Divide (Nums, mid+1, right);//To find the maximal and the intermediate continuous sub-sequences intMid_max = Nums[mid];//Left extension inttemp = Mid_max; for(inti = mid-1; I >= left; i--) {temp + = Nums[i]; Mid_max = Max (temp, Mid_max); }//Right extensiontemp = Mid_max; for(intj = mid+1; J <= Right; J + +) {temp + = Nums[j]; Mid_max = Max (temp, Mid_max); }returnMax (Mid_max, Max (Left_max, Right_max)); }};
Reference:
Https://github.com/soulmachine/leetcode
http://blog.csdn.net/xshengh/article/details/12708291
Leetcode | Maximum of Subarray maximal continuous sub-sequences