3. find the maximum and the sub-array
Title :
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 of the and of all sub-arrays. Requires a time complexity of O (n).
For example, the input array is 1,-2, 3, ten, -4, 7, 2,-5, and the largest subarray is 3, ten, -4, 7, 2,
So the output is the and of the subarray.
//starting with the first number plus, and credited as Sum, with a variable max record Max and, if and less than 0,sum=0, scan the entire array. #include <iostream>#include<cstdio>#include<limits>#include<vector>using namespacestd;#defineInt_min (numeric_limits<int>::min) ()intMain () {int_max=int_min,sum=0, Temp,i; Vector<int>_array; _array.reserve ( +);//set the container size to increase efficiency while(~SCANF ("%d",&temp)) { if(Temp>_max) _max=temp;//Record Maximum value_array.push_back (temp); } if(_max<=0) {printf ("the array's sub-array is the largest and is:%d\n", _max); return 0; } for(i=0; I<_array.size (); i++){ if(sum<0) sum=0; Sum+=_array[i]; if(Sum>_max) _max=sum; } printf ("the array's sub-array is the largest and is:%d\n", _max); return 0;}
Data structure and algorithm surface test questions 80 (3)