Title: Returns the and of the largest sub-array in an integer array.
Requirements:
Requires that the procedure be capable of handling 1000 elements;
Each element is of the int32 type;
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.
The maximum value for the and of all sub-arrays. Requires a time complexity of O (n).
Ideas:
Considering the manual input of 1000 elements, the system randomly 1000 elements are tested in the program. The code differs little from the previous code.
Program code:
1#include <iostream.h>2#include <stdlib.h>3 4 intMaxsum (intAintN)5 { 6 7 intsum=a[0];8 intb=0; 9 Ten for(intI=0; i<n; i++) One { A if(b<0)//... -b=A[i]; - Else theb+=A[i]; - if(sum<b) -sum=b; - } + returnsum; - } + A intMain () at { - intN; -cout<<"Please enter the number of elements in the array:"<<Endl; -Cin>>N; -cout<<"Please enter the elements of the array:"<<Endl; - int*a=New int[n]; in intx; - for(intI=0; i<n;i++) to { +X=rand ()-rand (); -a[i]=x; thecout<<a[i]<<" "; * } $ Panax Notoginsengcout<<Endl; -Cout<<maxsum (a,n) <<Endl; the + return 0; A}
Program:
Test for code overflow:
Will
int x; for (int i=0; i<n;i++) { x=rand ()-rand (); A[i]=x; cout<<a[i]<<""; }
Revision changed to
for (int i=0; i<n;i++) { cin>>a[i]; }
Program:
Feelings:
2^31-1=2147483647, the code overflows in the range of -2^31~2^31, beyond which is overflow. In the process of implementation of the program, mastered the use of random rand, using the call function, so that the program becomes "tall." But we still have room for improvement, so that we know more about it.
Returns the sum of the largest sub-arrays in an integer array