1 //Find maximum sub-sequence 4, -3,5,-2,-1,2,6,-22#include <stdio.h>3 intMax (intAintBintc)4 {5 intret;6 if(A >b)7 {8RET =A;9}ElseTen if(A <=b) One { ARET =b; - } - if(Ret >=c) the returnret; - Else - returnC; - } + intFindmaxsum (intBox[],intSizeintLeftintright)//parameter (array name, array size, left border - { + intMid = (right + left)/2; A if(left = =Right )//Divide the recursion to pay attention to export conditions at { - returnBox[left]; - } - intLeftsum =findmaxsum (Box,size,left,mid); To find out the maximal sub-sequence of the left half and to have recursive trust, do not tangle layers in depth, assuming that the function is correct. - intRightsum = findmaxsum (Box,size,mid +1, right); The maximal sub-sequence of the right half region and - intLeftbordersum =0; in intRightbordersum =0; - inti; to intThissum =0; + for(i = mid +1; I <= right;i++)//Find the maximal sub-sequence of the right half of the middle dividing point and (if the maximal sub-sequence crosses the intermediate dividing point, then it must contain the intermediate dividing point) - { theThissum + =Box[i]; * if(Rightbordersum <thissum) $ {Panax NotoginsengRightbordersum =thissum; - } the } +Thissum =0; A for(i = mid; I >= left;i--)//To find the maximal sub-sequence of the left half of the middle dividing point and the { +Thissum + =Box[i]; - if(Leftbordersum <thissum) $ { $Leftbordersum =thissum; - } - } the intMidsum = Leftbordersum +rightbordersum; The maximal sub-sequence across the left and right half regions and - returnMax (midsum,leftsum,rightsum); the largest sub-sequence of the left half and the largest sub-sequence of the right half, and the largest sub-sequence of the cross-section, and the largest of the three are the Seekers.Wuyi the - } Wu intMain () - { About intbox[8] = {4,-3,5,-2,-1,2,5,-2}; $ intRET =0; -ret = findmaxsum (box,8,0,7); -printf"%d", ret); - return 0 ; A}
Legacy problem, this algorithm has a time complexity of O (NLOGN). think about how to find out.
Divide-and-conquer method (for maximal subsequence and)