Solution One:Clear Test Instructions first:1. The title of the sub-array, is continuous. 2. The topic requires only and does not need to return the specific location of the subarray. 3. The elements of an array are integers, so the array may contain only positive integers, 0, negative integers.
For a few examples:array: [1,-2,3,5,-3,2] should return 8.array: [0,-2,3,5,-1,2] should return 9. array: [ -9,-2,-3,-5,-3] should return-2.
The most straightforward approach:Kee Sum[i,...., J] The sum of the elements of element A to the J element, (wherein 0<=i<=j<n), traversing all possible sum[i,... J], then the time complexity is O (N3).N3 represents the cubic of N. int Maxsum (int* A, int n)
{
int maximum =-inf;
int sum;
for (int i = 0; i < n; i++)
{
for (int j = i; J < N; j + +)
{
for (int k = i; k <= J; k++)
{
Sum + = A[k];
}
if (Sum > maximum)
Maximum = sum;
}
}
return maximum;
}
improvement of method one: because Sum[i,..., j]=sum[i,..., j-1]+a[j]. You can omit the last for loop in the algorithm. The time complexity is O (N2). N2 is the square of N. The code is as follows:
int maxsum (int *a, int n)
{
int maximum =-inf;
int sum;
for (int i = 0; i < n; i++)
{
sum = 0;
for (int j = i; J < N; j + +)
{
Sum + = A[j];
if (Sum > maximum)
Maximum = sum;
}
}
return maximum;
}
Solution Two:
Solution Three:
a hint from the divide-and-conquer algorithm: Consider the first element of the array a[0], and the relationship between the largest array (A[i],...., a[j]) and a[0].
There are several situations:
Solution Two:
int max (int x, int y)
{
Return (x>y)? x:y;
}
int Maxsum (int* A, int n)
{
Start[n-1] = a[n-1];
All[n-1] = a[n-1];
for (i = n-2; I >= 0; i--)
{
Start[i] = max (A[i], A[i] + start[i + 1]);
All[i] = max (Start[i], all[i + 1]);
}
return a[0];
}
the time complexity of the new method is: O (N)But there is a new problem, the additional application of two arrays all[],start[], can you save space?
int max (int x, int y)
{
Return (x>y)? x:y;
}
int Maxsum (int* A, int n)
{
Nstart = a[n-1];
Nall = a[n-1];
for (i = n-2; I >= 0; i--)
{
Nstart = Max (A[i], a[i] + nstart);
Nall = Max (Nstart, Nall);
}
return nall;
}
In other way:int Maxsum (int* A, int n)
{
Nstart = a[n-1];
Nall = a[n-1];
for (i = n-2; I >= 0;i--)
{
if (Nstart < 0)
Nstart = 0;
Nstart + = A[i];
if (Nstart > Nall)
Nall = Nstart;
}
return nall;
}
Extensions:
The maximum value of the sum of the subarray of the array