Design ideas:
You only need to loop the one-dimensional array around, and find out the sum of the largest sub-arrays.
Expand this one-dimensional array by twice times, and after this one-dimensional array, continue to follow the one-dimensional array.
Since it is a circle, the length of the array is constant, so only the number of cycles can be limited.
Problems that arise:
Limits the number of loops in the process of finding the largest subarray. If you simply limit the loop n times (n array length), some data will be in error.
Source:
1//Xiaosong Du 2015/4//112 #include <iostream>3 #include <time.h>4UsingNamespaceStd5#define N 1067voidMain ()8{9int a[2*n],d =0,D1 =0;10int Maxd, End2 =0,end1[2*n]={0};11Int J =-1,j1 =0,j2 =-1;//J Record positive integer negative subscript, J2 record the largest array before the sum of negative subscriptSrand (unsignedint) Time (0));1314for (int i =0;i < n;i++)15{A[i] = rand ()%50-25;A[i+n] =A[i];18}19for (int i =0;i < n;i++)20{cout << A[i] <<",";22}cout <<Endl24Maxd = a[0];26for (int i =0;i <2*n;i++)27{-D + =A[i];29if (d >MAXD)30{Maxd =DEND1[J1] =Ij1++;J2 =J35}36if (D <0)37{D =0;j =I40}4142if (end1[j1-1]-J2 > N)//If END1[J1-1]-J2 is greater than N, then get end1[j1-2]43{j1--;45Break;46}47}cout <<EndlEnd2 = j2+1;50Wuyi cout <<"The maximum number of sub-arrays is:";52for (int i = End2;i <= end1[j1-1];i++)53{54if (i > N-1)55{cout <<"The"<< i+1-n <<"";57}58Else59{cout <<"The"<< i+1 <<"";61}62}cout <<", these numbers are composed."<<Endl<< coutEndl65 cout << " "; for (int i = end2;i <= end1[j1-1];i++) "" ; Endl; cout << " and: " << maxd << Endl; 70}
Operation Result:
Summarize:
Position subscript has always been a problem when doing position positioning. If the number of n per cycle (n array length), the time complexity of the need O (n^2), not satisfied, to go. So in the case of the maximum subarray, with the condition limit, the maximum length is n when the largest sub-array appears. The problem is resolved accordingly. But the idea came out, but there were problems in the process. Constantly experimenting, changing the code, took a morning's time to finally solve. The algorithm is more concise than before, but the time complexity is still O (n).
Team Photo:
Returns the and (ring) of the largest sub-array in an integer array