The contiguous maximum sub-segments of an array and

Source: Internet
Author: User

  Problem Description : The input is an integer array of size n, which requires the maximum value in any contiguous subarray of the output array. For example: Enter an array of array[10] = {31,-41,59,26,-53,58,97,-93,-23,84}; output a maximum contiguous subarray and a array[2...6]:187

  Algorithm 1: iterates over all 0<=i<=j<=n (i,j) integer pairs, computes the sum of ARRAY[I...J] for each integer pair, and verifies that the sum is greater than the maximum sum to date.

The pseudo-code for algorithm 1 is described below:

0 for(i=0;i<n;++J) for(j=i;j<n;++J)0 for(k=i;k<=j;++k)6 TempSum + = Array[k]7 Maxsofar = max (Maxsofar,tempmax)         

This code is straightforward and understandable, but the program executes slowly and with a time complexity of O (n^3).

  algorithm 2: for algorithm 1 There is an obvious way to make it run much faster. Allows time complexity to control square O (n^2).

The first squared algorithm notes that the sum of ARRAY[I...J] is closely related to the sum previously computed (array[i...j-1]), which can be achieved with algorithm 2.

The pseudo-code of the algorithm 2_1 is described as follows:

0 for(i=0;i<n;++i)0;  For (j=i;j<n;++J)5 tempsum + = Array[j]6 maxsofar = max (maxsofar,tempsum)   

The second square algorithm is to introduce an array of Curarray, the size is also n, through the space to exchange time, by accessing the outer loop execution before calculating [0...i] each successive field sum. The first element in Curarrary contains the sum of the numbers in array[0...i], so the summation of the individual numbers in X[I...J] can be obtained by calculating CURARRAY[J]-curarray[i-1].

The pseudo-code of the algorithm 2_2 is described as follows:

1 curarray[-1] = 02 for (I=0;i<n;++i) 3 curarray[i] = Curarray[i-1]+ x[i]4 Maxsofar = 05 for (I=0;i<n;++i) 6 for (j=i;j<n;++j) 7 sum = Curarray[j]-curarray[i-1]8 Maxsofar = max (maxsofar,sum)       

  Algorithm 3: The rule of law algorithm can be considered. The initial problem is to handle an array of size n, so it can be divided into two sub-arrays A and B, and then recursively find the largest number of elements in A and B, respectively, Maxa, MAXB. The largest subarray is either in a, or B, or across the boundary between A and B, and we count the largest sub-array across the boundary as MAXC. We calculate the Maxa and MAXB by the divide-and-conquer algorithm, and calculate the branch maxc by some means. And then return the maximum value in three is the maximum number of sub-arrays we want and. The time complexity of the algorithm is O (NLOGN). How to calculate MAXC? It is observed that the part of MAXC in a is the largest subarray of the right boundary in a, and the part of MAXC in B is the largest subarray in B that contains the left boundary. Combining these together we get algorithm 3:

1int maxsum3 (1, N)2{3if (n<1)//Empty array4Return05if (n==1)6//An array of only one element7Return array[1]8 mid = n/2//Divided into two parts9 Lmax = TempSum =010//The largest sub-array containing the right boundary and the11for (i=mid;i>=1;--i) 12 sum + Array[i]13 Lmax =< Span style= "COLOR: #000000" > Max (lmax,sum) 14 rmax = sum =0; // contains the largest subarray of the left boundary and 15 for (I=mid;i<n;++i) 16 sum +=< Span style= "COLOR: #000000" > Array[i] 17 rmax = Max (Rmax, SUM) 18 return Max (lmax+rmax,maxsum3 (1,mid), maxsum3 (Mid+1,n)) 19}             

  Algorithm 4: We now take the simplest algorithm of manipulating an array: Start scanning from the leftmost (element x[0]) of the array, up to the far right (element array[n-1]), and note the sub-array of the largest sum encountered. The maximum sum starts at 0. Suppose we have solved the problem of array[0...i-1], so how do we extend it to include X[i]? We use a principle similar to the divide-and-conquer algorithm: In the first I element, the maximum sum of the subarray is either in the first I-1 element (which is stored in maxsofar), or it ends at I (depositing it into the maxendinghere). Instead of starting from scratch, the largest sub-array ending at I is calculated using the largest subarray of i-1 at the end position. This gives you the algorithm 4:

00for (i=0;i<n;++i)4 maxendinghere = max (maxendinghere+array[i],0)5 Maxsofar = max (maxsofar,maxendinghere)       

The key to understanding this program is maxendinghere. Before the first assignment statement in the loop, Maxendinghere is the and of the largest subarray whose end position is i-1, and the assignment statement modifies it to the and of the largest subarray with the ending position of I. If the result is a positive value after adding array[i], the assignment statement causes Maxendinghere to increase x[i], and if the result is negative after adding x[i], the assignment statement sets Maxendinghere back to 0 (because the largest sub-array ending position I is now empty). This place has some difficulty and needs to be considered carefully. Time complexity is O (n), linear algorithm, the most efficient.

The following 4 algorithms to write a completed program to test, the program is as follows:

1. #include <iostream>2Usingnamespace Std;//Ask for two number of maximum values3int Max (Constint m,ConstIntN4{5Return m>n?m:n;6}//To find the maximum value in three integers7int Max (Constint x,Constint y,ConstIntZ8{9int temp = X>y?x:y;temp = temp > z?Temp:z;11ReturnTemp12}//Algorithm 1 function implementation13int Maxsum1 (int *array,Constsize_t len)14{15int Maxsofar =0;16int tempsum =0;17for (size_t i=0;i<len;++I18for (size_t j=i;j<len;++J19{TempSum =0;21stFor (size_t K =i;k<=j;++K22{23°c TempSum + =ARRAY[K];Maxsofar =Max (maxsofar,tempsum);25}26}27ReturnMaxsofar;28}//Implementation of Algorithm 2.129int Maxsum2_1 (int *array,Constsize_t len)30{31int Maxsofar =0;32int tempsum =0;33for (size_t i=0;i<len;++I34{TempSum =0;36for (size_t j=i;j<len;++J37{TempSum + =ARRAY[J];Maxsofar =Max (maxsofar,tempsum);40}41}42ReturnMaxsofar;43}//Implementation of Algorithm 2.244int Maxsum2_2 (int *array,Constsize_t len)45{46int *curarray =NULL;47int Maxsofar =0;48if (len>0)Curarray =NewInt[Len];curarray[-1] =0;51for (size_t i=0;i<len;++ICurarray[i] = curarray[i-1] +Array[i];53for (size_t j=0;j<len;++J54for (size_t k=j;k<len;++K55//TempSum = Curarray[k]-curarray[j-1];Maxsofar = Max (maxsofar,curarray[k]-curarray[j-1]);57ReturnMaxsofar;58}//Implementation of Algorithm 359int maxsum3 (int *array,Constint begin,ConstIntEnd60{61int mid =0; Lmax=0,rmax int = 0; TempSum int = 0; if (begin==end)-array[begin]; The MID = (begin+end)/2; (int i=mid;i>=begin;--i) TempSum + = Array[i]; Lmax = max (lmax,tempsum); tempsum = 0; J=mid+1;j<=end;++j (int) TempSum + = Array[j], Rmax = max (rmax,tempsum), and the return Max (lmax+rmax,m AXSUM3 (Array,begin,mid), maxsum3 (Array,mid+1,end)); 79}//The implementation of the algorithm 4 is maxsum4 int (int *array,const size_t len) bayi {0 int maxendinghere = 0; T i=0;i<len;++i) (Maxendinghere = max (maxendinghere+array[i],0); Maxsofar = max (Maxsofar,maxendinghere); 88} Maxsofar return; The "n} int main ()" () "array[10" = {31,-41,59,26,-53,58,97,-93,-23,84}; choise int, 94 cout<< "1. Algorithm 1" << Endl cout<< "2. Algorithm 2_1" <<endl; cout<< "1. Algorithm 1" <<endl; cout<< "3. Algorithm 3" <<endl; 98 cout<< "4. Algorithm 4" <<endl; cout<< "5. Algorithm 2_2" <<endl;100 cout<< "0. Exit" <<endl;101 while (1) 102 {103 cout<< "selection algorithm:"; 104 cin>>choise;105 cout<< "The maximum field of the array is:"; 106 switch ( Choise) 107 {108 Case 1:109 cout<<maxsum1 (array,10) <<endl;110 break;111 case 2:112 Cout<<maxsum2_1 ( array,10) <<endl;113 break;114 case 3:115 cout<<maxsum3 (array,0,9) <<endl;116 break;117 case 4:118 COUT&LT;&LT;MAXSUM4 (array,10) <<endl;119 break;120 case 5:121 cout<<maxsum2_2 (array,10) <<endl;122 break;123 Case 0:124 exit (0),}126}127 return 0;128}

Reference: "Programming Zhu Ji Nanxiong" The second edition of the eighth chapter of the Art of algorithmic design

The contiguous maximum sub-segments of an array and

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.