First, the design idea: the length of the input array and the range of values in the group, a random array is generated, and a random number determines the sign. Then in a loop, the number of the array is added sequentially, if the sum of more than 0 continue to add, if the sum of less than 0 discard the previous number, start adding again, and in the loop record the maximum number of additions, that is, the sum of the largest subarray.
Second, code: #include <iostream>
using namespace Std;
void Main ()
{
int i,x,y,z;
int s,sum,head,end,h,e;
cout<< "Please enter the length of the array:";
cin>>x;
cout<< "Please enter the range of values for the array:";
cin>>z;
int *a=new int[x];
if (x==0)
{
cout<< "Error" <<endl;
return 0;
}
for (i=0;i<x;i++)
{
A[i]=rand ()%z;
Y=rand ()%2;
if (y==0)
{
A[i]=-a[i];
}
}
sum=0;
s=0;
e=0;
h=0;
for (i=0;i<x;i++)
{
S+=a[i];
if (s>0)
{
e++;
}
Else
{
Q=r;
h=i+1;
e++;
}
if (s>sum)
{
Sum=s;
Head=h;
End=e;
}
}
cout<< "The number of the largest sub-arrays is:" <<sum<<endl;
Delete A;
}
Iii. results:
Iv. code testing and emerging issues
1. The program cannot run when the input array has a length of 0 or is negative.
2. When the sum of the random numbers is not within the range of the Int32, only the maximum number is displayed
V. Methods of Solution
1, the input number with if statement to judge, if not meet the conditions, the direct termination of the program
2, for the sum of the random number of large or small can not be displayed, should be adjusted by the random number range to reduce the sum of random numbers
Vi. Summary
This time the test of the original program to me a lot of inspiration, especially the logarithm of the range of the decision and the number of input constraints, let me in the future development of the program can notice some small details, to avoid large errors.
Vii. team members: DUYONGSU, Guo Hao
Team Photo:
Maximum sub-array program two