Solving the problem of maximal sub-array--the solution of violence and divide-and-conquer method

Source: Internet
Author: User

/*------------------solve the maximum subarray problem---------------the largest subarray, which is the combination of all the elements of an array, and the largest subarray. In this case, if the element value is all non-negative, then the maximum subarray is of course all elements. However, if there are negative elements, then it is necessary to find a sub-array consisting of several successive elements in the array and the sum of the values of the elements. */#include<iostream>using namespacestd;structarraystruct {arraystruct (intb =0,intE =0,ints =0): Begin (b), End (e), sum (s) {}intbegin; intend; intsum;};/*method One: First, the simplest of course is the brute force solution, in this case, the complexity of the algorithm is O (n^2), the code as shown in the function Subarrayrough. */arraystruct Subarrayrough (int*array,intlength) {    intsum =-999999; intbegin, end;  for(inti =0; I! = length; ++i) {intSumtemp =0;  for(intj = i; J! = length; ++j) {Sumtemp+=Array[j]; if(Sum <sumtemp) {Begin=i; Sum=sumtemp; End=J; }        }    }    returnarraystruct (begin, end, sum);}/*  Method Two is the use of divide and conquer method: Join us to find the largest array of A[low, high] sub-array, using divide-and-conquer technology means to divide the original array, that is, the original array into the same scale as the same sub-array. Then, you need to find the focus mid of the original array, and then work on the left and right side of the original array, respectively. Then, the maximum sub-array position must be one of the following three cases "I, j for the result range subscript": ·    Exactly in sub-array a[low, mid], so low <= I <= J <= Mid. ·    Exactly in sub-array A[mid + 1, high], so mid < I <= J <= High. · Across the midpoint, so low <= I <= mid < J <= High in fact, the largest subarray of array A is necessarily the largest of the above three cases.    So, we just need to find the largest of the three cases above. So, we can recursively solve the maximum subarray of sub-array a[low, Mid],a[mid + 1, high], because this is still the largest subarray problem, and then the value of both and the two and the midpoint of the group array of three to find the maximum value. So, we are going to deal with three cases, A[low, Mid],a[mid + 1, high] and including the midpoint of three cases. The pseudocode is as follows: Find-maximum-subarray (A, low, high): if high = = Low:return (low, High, a[low])//Only one element, then the maximum value is this Element value Else mid = [(low + High)/2] (Left-low, Left-high, left-sum) = Find-maximum-subarray (A, Low, mid) ( Right-low, Right-high, right-sum) = Find-maximum-subarray (A, mid + 1, high) (Cross-low, Cross-high, cross-sum) = FI Nd-maximum-crossing-subarray (A, Low, mid, high) if Left-sum >= Right-sum && left-sum >= Cross-sum:return (Left-low, Left-high, left-sum) if Right-sum >= right-sum && right-sum >= Cross-sum:return (Right-low, Right-high, right-sum) Else return ( Cross-low, Cross-high, Cross-sum) wherein, the function Find-maximum-crossing-subarray pseudo-code as follows, in fact its function is to find the largest sub-array containing the mid element, so long can be directly from    Mid departure to both sides look for: Find-maximum-crossing-subarray (A, Low, Mid, high): Left-sum =-∞sum = 0;    For i = Mid Downto low:sum + = A[i] If left-sum < sum:left-sum = Sum Max-left = i    right-sum =-∞sum = 0; For i = mid + 1 to high:sum + = A[i] If right-sum < sum:right-sum = Sum max-right = I return (max-left, max-right, Left-sum + right-sum) The code is not difficult to write according to the pseudo code. The time complexity of Find-maximum-crossing-subarray is linear, and Find-maximum-subarray is a division method, and the main method of calculating the time complexity of divide-and-conquer method T (N) = at (n/b) + f (n) can be known because a = = b = = 2 So the time complexity is log (n), so the total time complexity is n (log (n))*/arraystruct Findmaximumcrossingsubarray (int*array,intLowintMidintHigh ) {    intLeftsum =-99999; intsum =0, Leftmax =Low ;  for(inti = mid; I >=0; --i) {sum+=Array[i]; if(Sum >leftsum) {Leftsum=sum; Leftmax=i; }    }    intRightsum =-99999; Sum=0; intRughtmax =High ;  for(inti = mid +1; I <= high; ++i) {sum+=Array[i]; if(Sum >rightsum) {Rightsum=sum; Rughtmax=i; }    }    returnArraystruct (Leftmax, Rughtmax, Leftsum +rightsum);} Arraystruct Findmaximumsubarray (int*array,intLowintHigh ) {    if(High = =Low ) {        returnarraystruct (Low, High, array[low]); } Else {        intMid = (low + high)/2; Arraystruct Left=Findmaximumsubarray (Array, low, mid); Arraystruct Right= Findmaximumsubarray (array, Mid +1, high); Arraystruct Cross=Findmaximumcrossingsubarray (Array, Low, mid, high); if(Left.sum >= right.sum && left.sum >=cross.sum)returnLeft ; Else if(Right.sum >= right.sum && right.sum >=cross.sum)returnRight ; Else            returnCross ; }}intMainintargcChar Const*argv[]) {cout<<"Input the size of the array:"; intarraySize; int*Array; CIN>>arraySize; Array=New int[ArraySize];  for(inti =0; I! = arraySize; ++i) Cin>>Array[i]; Arraystruct a=Subarrayrough (array, arraySize); cout<<"result of rough found:"<< Endl <<'\ t';  for(inti = A.begin; I <= a.end; ++i) {cout<< Array[i] <<" "; } cout<<Endl; cout<<"result of minute found:"<< Endl <<'\ t'; Arraystruct b= Findmaximumsubarray (Array,0, ArraySize-1);  for(inti = B.begin; I <= b.end; ++i) {cout<< Array[i] <<" "; } cout<<Endl; return 0;}

Solving the problem of maximal sub-array--the solution of violence and divide-and-conquer method

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.