"Introduction to Algorithms" Maximum sub-array

Source: Internet
Author: User

1. Description: Find the array A and the largest non-empty continuous subarray, we call such a continuous sub-array is the largest sub-array.

  

2. Use the divide and conquer strategy to solve.

A. Suppose we require a sub-array of A[low, high] for the largest subarray. According to the divide-and-conquer strategy, we divide the A[low,high first.

B. A[low,highj] Sub-array a[i,j] There are only three possible

A) completely located in A[low, mid]; At this time low <= I <= J <= mid

b) completely in a[nid+1, high], at this time mid + 1 <= i <= J <= High

c) across mid mid, at this time low <= I <= mid < J < High

3. Pseudo-code

find-maximum-Subarray (A, Low, high)ifHigh = =Low return (low, high. A[low])//only one element    ElseMid= (low + high)/2     //Rounding down(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) = find-max-crossing-Subarray (A, Low, Mid, high)ifleft-sum>= right-sumand left-sum>= cross-sumreturn ( left-low, Left-high, left-sum)        Else ifright-sum>= left-sumand right-sum>= cross-sumReturn ( right-low, Right-high, right-sum) return ( Cross-low, Cross-high, cross-sum) FIND-max-crossing-Subarray (A, Low, Mid, high) left-sum= -∞sum=0     fori =Mid Downto Lowsum=sum+A[i]if sum> left-sum Left-sum=sumMax-left =I right-sum= -∞sum=0;  forj = Mid +1 to Highsum=sum+A[j]if sum> right-sum Right-sum=sumMax-right =J return (Max-left, Max-right, left-sum+ right-sum)

4. Analysis

As I said before, all comparisons are finally two-digit comparisons. The largest sub-array through the division of the strategy is finally an element, this is the direct return of this number, to the previous layer.

This time the array has two numbers, the sub-array to 2 said the comparison of three cases, and then a layer of upward submission of results

5. Code implementation

Java

 Public classMaxarray {Private Static classResult {intLow ; intHigh ; intsum;  PublicResult (intLowintHighintsum) {             This. Low =Low ;  This. High =High ;  This. sum =sum; }    }    StaticResult Findmaximumsubarray (int[] A,intLowintHigh ) {        if(Low = =High ) {            return NewResult (Low, High, a[low]); } Else {            intMid = (low + high)/2; Result Leftresult=Findmaximumsubarray (A, Low, mid); Result Rightresult= Findmaximumsubarray (A, mid+1, high); Result Crossresult=Findmaxcrossingsubarray (A, Low, Mid, high); if(Leftresult.sum >= rightresult.sum && leftresult.sum >=crossresult.sum)returnLeftresult; Else if(Rightresult.sum >= leftresult.sum && rightresult.sum >=crossresult.sum)returnRightresult; Else returnCrossresult; }    }    StaticResult Findmaxcrossingsubarray (int[] A,intLowintMidintHigh ) {        //Test left        intLeftsum = Integer.min_value;//Sentinel        intMaxleft =mid; intsum = 0;  for(inti = mid; I >= low; i--) {sum+=A[i]; if(Sum >leftsum) {Leftsum=sum; Maxleft=i; }        }        //Test Right        intRightsum =Integer.min_value; intMaxright = mid + 1; Sum= 0;  for(intj = mid + 1; J <= High; J + +) {sum+=A[j]; if(Sum >rightsum) {Rightsum=sum; Maxright=J; }        }        //Combine The results of the two sides together        return NewResult (Maxleft, maxright, Leftsum +rightsum); }     Public Static voidMain (string[] args) {int[] A = {-1, 5, 6, 9, 10,-9,-8, 100,-200}; Result result= Findmaximumsubarray (A, 0, A.length-1); System.out.println (Result.low+ "," + Result.high + "" +result.sum); }}

Python

defFind_maximum_subarray (nums, Low, high):ifLow = =High :return{" Low": Low," High": High,"sum": Nums[low]}Else: Mid= Int (low + high)/2) Left_result=Find_maximum_subarray (Nums, Low, mid) Right_result= Find_maximum_subarray (Nums, Mid + 1, high) Cross_result=Find_max_crossing_subarray (Nums, Low, Mid, high)ifleft_result["sum"] >= right_result["sum"] andleft_result["sum"] >= cross_result["sum"]:            returnLeft_resultElse:            ifright_result["sum"] >= left_result["sum"] andright_result["sum"] >= cross_result["sum"]:                returnRight_resultElse:                returnCross_resultdefFind_max_crossing_subarray (Nums, Low, Mid, high): Left_sum=-float ('inf') Total=0 Max_left=Mid forIinchRange (Mid, low-1, 1): Total+=Nums[i]ifTotal >Left_sum:left_sum=Total max_left=I rigth_sum=-float ('inf') Total=0 Max_right= Mid + 1 forJinchRange (mid+1, high+1): Total+=Nums[j]ifTotal >Rigth_sum:rigth_sum=Total max_right=Jreturn{" Low": Max_left," High": Max_right,"sum": Left_sum +Rigth_sum}if __name__=="__main__": Numss= [-1, 5, 6, 9, 10,-9,-8, 100,-200] Result= Find_maximum_subarray (NUMSS, 0, Len (NUMSS)-1)    Print(Result)

Another way to share a python slice

defFind_maximum_subarray_slice (nums): Max_sum=-float ('inf') Result= {}     forIinchRange (len (nums) +1):         forJinchRange (I, Len (nums) +1): Total=sum (nums[i:j])ifTotal >Max_sum:max_sum=Total result[" Low"] =I result[" High"] = J-1result["sum"] =Max_sumreturnResult

C language

The structure did not learn well, late post.

"Introduction to Algorithms" Maximum sub-array

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.