For example, for an array [1,-2,3,5,-1,2] Maximum sub array and is sum[3,5,-1,2] = 9, we require the function to output the substring and the maximum value, and to return the left and right edges of the array (the following function, the back-and-right argument).
In this article we stipulate that when all the numbers in an array are less than 0 o'clock, the largest number in the array is returned (or it can be specified to return 0, as long as the maxsum in the following code is initialized to 0), we should pay attention to the case of 1 0 0 0-2, especially if the output of the If it's an interview, ask the interviewer for clarity.
The following code we have in Pat 1007. Maximum subsequence The sum test passes, the test main function is as follows
int main ()
{
int n;
scanf ("%d", &n);
Vector<int>vec (n);
for (int i = 0; i < n; i++)
scanf ("%d", &vec[i]);
int left, right;
int maxsum = MAXSUM1 (VEC, left, right);//Replace function name
if (maxsum >= 0)
printf ("%d%d%d", Maxsum, Vec[left), Vec[r Ight]);
else printf ("0%d%d", vec[0], vec[n-1]);
Reference: Programming Beauty 2.14 The maximum value for the sum of the array's child arrays
Algorithm 1: The simplest is to raise all of the child arrays, and then sum up, the complexity is O (n^3)
int maxSum1 (Vector<int>&vec, int &left, int &right)
{
int maxsum = int_min, sum = 0;
for (int i = 0; i < vec.size (); i++) for
(int k = i; k < vec.size (); k++)
{
sum = 0;
for (int j = i; J <= K; j +)
sum + = vec[j];
if (Sum > Maxsum)
{
maxsum = sum;
left = i;
right = k;
}
}
return maxsum;
}
Algorithm 2: The above code third cycle does a lot of repetitive work, slightly improved as follows, the complexity of O (n^2)
int maxSum2 (Vector<int>&vec, int &left, int &right)
{
int maxsum = int_min, sum = 0;
for (int i = 0; i < vec.size (); i++)
{
sum = 0;
for (int k = i; k < vec.size (); k++)
{
sum + = vec[k];
if (Sum > Maxsum)
{
maxsum = sum;
left = i;
right = k;
}
}} return maxsum;
}