Maximum sub-array program two

Source: Internet
Author: User

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

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.