Knot pair Member
Cao Kun Kaikai
Topic
Returns the and of the largest sub-array in an integer array.
Requirements:
Enter an array of shapes with positive and negative numbers in the array.
One or more consecutive integers in an array make up a sub-array, each of which has a and.
If the array a[0]... A[j-1] next to each other , allowing a[i-1], ... a[n-1], a[0]... A[j-1] and the largest.
Returns the position of the largest subarray at the same time.
Ideas
After discussion, simply extend the array to twice times the length, array[i]=array[length+i]; start with the first element
The next five elements are grouped into five groups, each of which is divided into five maximum sub-arrays, and then the maximum value is calculated. This method
It is easy to solve the problem, but the number of groups is the number of elements, that is, to cycle the length of the calculation. However, I
It is found that the element before the first element of the maximum subarray must be negative, otherwise the entire array is a positive number, so a
In an array of loops with large enough elements, there is a way to save the computational amount by simply considering the latter element of the negative elements
If the element is a positive number, the maximum value is calculated by starting five elements of the element in the array, that is, the count of loops
It is related to the number of negative numbers without having to loop length.
Code
#include <iostream>#include<conio.h>#include<ctime>#defineMax_length 10using namespacestd;intMain () {srand (unsigned) time (NULL)); int* arr=New int[2*Max_length]; intresult=0, r,sum,k=0, l=0, g=0, a,b=0, flag=0; intrandoms,count1=0, count2=0, c1=0, c2=0; while(1) {cout<<"randomly generated"<<Max_Length<<"values: \ n"<<Endl; for(intI=0; i<max_length; i++) {randoms= (-rand ()% -+ (rand ()% - )); Arr[i]= Arr[i+max_length] =randoms; cout<<"array Elements"<<i+1<<"the following were:"<<arr[i]<<Endl; } for(ints=0; s<max_length; s++) { if(arr[s]<0&& g==s) {g++; if(a<Arr[s]) {a=Arr[s]; } if(g==max_length) {cout<<"The sum of the largest arrays:"<<a<<endl<<Endl; } } if(arr[s]>0&& l==s) {L++; b+=Arr[s]; if(l==max_length) {cout<<"The sum of the largest arrays:"<<b<<endl<<Endl; } } if(arr[s]<0&& arr[s+1]>=0) {flag=1; R=arr[s+1]; Sum=0; for(intt=0, j=s+1; j<s+max_length+1; J + +) {T++; if(sum>=0) {sum+=arr[j];} Else{C1=j; sum=arr[j];} if(R <sum) {Count1=C1; Count2=C2; R=sum; } } if(result<r) {result=R; } } } if(flag==1) cout<<"the sum of the largest array 3:"<<result<<endl<<Endl; Result=a=b=arr[0]; Getch (); } return 0;}
Summarize
My companion and I had actually thought of the solution before, and this was my last thought, when the array element was large enough,
Will effectively save the number of calculations. So I think the method is always there, but to find a better way is to think more.
Loop array of the end-to-end to find the maximum of its sub-array