Solving the maximal and solution of sub-array _c language

Source: Internet
Author: User
Tags arrays
Topic: Enter an array of integers with positive and negative numbers in the array. One or more consecutive integers in an array form a child array, each of which has a and. The maximum value of the and of all child arrays is evaluated. Requires a time complexity of O (n).
For example, the input array is 1,-2, 3, 10,-4, 7, 2,-5, and the largest sub array is 3, 10,-4, 7, 2, so the output is the and 18 of the sub array.
If time complexity is not considered, we can enumerate all the sub arrays and find out their and. Unfortunately, because an array of length n has an O (N2) array, and the time complexity of an array of length n is O (n). So the time of this idea is O (N3).
It is easy to understand that when we add a positive number, it increases; when we add a negative number, it is reduced. If the current sum is negative, then this and the next addition should be discarded and cleared again, otherwise the negative will decrease the sum of the following. Based on this idea, we can write the following code:
Copy Code code as follows:

/*
Find the greatest sum of all sub-arrays
Return value:if The "input is valid" return true otherwise return false
int *pdata,//an array
unsigned int nlength,//The length of array
int &ngreatestsum//The greatest sum of all sub-arrays
*/
int start,end;
BOOL Findgreatestsumofsubarray (int *pdata, unsigned int nlength, int &ngreatestsum)
{
If the input is invalid, return false
if ((PData = NULL) | | (nlength = 0))
return false;
int k=0;
int ncursum = Ngreatestsum = 0;
for (unsigned int i = 0; i < nlength; ++i)
{
Ncursum + = Pdata[i];
If the current sum is negative, discard it
if (Ncursum < 0)
{
ncursum = 0;
K = i+1;
}
If a greater sum is found, update the greatest sum
if (Ncursum > Ngreatestsum)
{
Ngreatestsum = Ncursum;
start = k;
end = i;
}
}
If all data are negative, find the greatest element in the array
if (ngreatestsum = 0)
{
Ngreatestsum = pdata[0];
for (unsigned int i = 1; i < nlength; ++i)
{
if (Pdata[i] > Ngreatestsum)
{
Ngreatestsum = Pdata[i];
Start = end = i;
}
}
}
return true;
}

Discussion: There are two points in the above code that are worth discussing:
• The return value of a function is not the maximum value of a child array, but rather a flag that determines whether the input is valid. If the function returns the value of the child array and the maximum value, what should be returned when a null pointer is entered? return 0? So how does the user of this function differentiate between the input invalid and the maximum value of the sub array and the 0? Based on this consideration, I think that the array of the handle and the maximum value are referred to the list of parameters, and let the function return a function whether the normal execution of the flag.
• Special handling is required for a particular type of input. When all the integers in the input array are negative, the maximum value of the child array and the largest element in the array is the largest.
Method Two: The beauty of programming 2.14
Copy Code code as follows:

/**
Find the maximum sub array and (Programming beauty 2.14, return subscript and not connected)
* * Author:liuzhiwei
* * DATE:2011-08-17
How to record the start and end points:
Because I want the starting point subscript, the end point subscript all the preceding sub array, so we are best at the time of dynamic planning from backward forward, so that the value of Dp[i] is the following is the value of the largest sub array starting with subscript I, then when Dp[i] and dp[j] We select the smaller subscript in I,j as the starting point
**/
int maxsum (int *arr, int n, int & start, int & end)
{
int I, temp, DP, Max;
DP = max = arr[n-1];
Start = end = N-1;
temp = n-1;
for (i = n-2 i >= 0; i.)
{
if (DP > 0)
DP = Arr[i];
Else
{
DP = Arr[i]; Discard Current child sequence
temp = i; Start a new child sequence search
}
if (DP > Max)//update maximum subsequence
{
max = DP;
end = temp;
start = i; Maximum and increase, at this time I must be the right end
}
}
return Max;
}
Special test Cases-10-1-4

Another way to traverse backwards is as follows:
Copy Code code as follows:

When you need to save the start and end point subscripts, it's OK to traverse backwards.
int maxsum (int *a, int n)
{
int tempstart = 0, sum=0, max =-1000;
int I, start, end;
Start = end = 0;
for (i = 0; i < n; ++i)
{
if (Sum < 0)
{
sum = A[i];
Tempstart = i;
}
Else
Sum + + a[i];
if (Sum > Max)
{
max = sum;
start = Tempstart;
end = i;
}
}
return Max;
}

extension Question 1:
If the array is considered to be circular, that is, the end-to-end (the element following the subscript n-1 is labeled 0), the maximum segment and.
Analytical:
I think this problem is easier than the first one and there are many ways to solve it. I introduced three methods, but one that I felt was problematic, but as an exercise in the book "The Beauty of programming," it may be that I have misunderstood the author's algorithm and will discuss it slowly.
Method One:
The optimal solution to this problem must be the following two possibilities. Probably one: the optimal solution does not span a[n-1] to a[0], i.e. the original problem, the non circular array. Possible two: The optimal solution crosses a[n-1] to a[0], new problem.
For the first case, we can be obtained according to the simple dynamic programming method, set to Max1; for the second case, you can transform the original problem into the most small segment and the problem of the array, then use the sum of the elements of all the arrays and subtract the most small segments, then the result must be the largest segment of the a[n-1 to a[0] case and set to MAX2. The final result is the larger of Max1 and MAX2.
Example 1: There are arrays 6,-1,-6, 8, 2
Obtain max1=10,max2=16, then take the larger max2 as the result.
Example 2: There are arrays-6, 8, 2, 6,-1
Obtain max1=16,max2=15, then take the larger max1 as the result.
Some of the alumni may have questions about why: The largest segment of the array element "sum-the most small segment and = across a[n-1] to a[0] case". We can understand that: the number of N and is certain, then if we find in the number of consecutive numbers, and this number is all consecutive numbers and the smallest, then the "sum-the youngest section and" The result must be the largest. So we get: the maximal sub-segment of the case of crossing a[n-1] to a[0].
The complete code is as follows:
Copy Code code as follows:

The and of the maximal sub array for the ring array
int maxsum (int *a, int n)
{
int i, SUM, MAX1, MAX2, DP, Min;
DP = MAX1 = a[0];
for (i = 1; i < n; ++i)//optimal solution does not span a[n-1] to a[0], that is, the original problem, non-circular array
{
if (DP < 0)
DP = A[i];
Else
DP = A[i];
if (DP > MAX1)
MAX1 = DP;
}
sum = min = DP = a[0];
for (i = 1; i < n; ++i)//You can transform the original problem into the most small segment and the problem of the array, then use the sum of the elements of the arrays and subtract the most small segments, then the result must be the largest segment of the a[n-1 to a[0] case and
{
if (DP > 0)
DP = A[i];
Else
DP = A[i];
if (DP < min)
min = dp;
Sum + + a[i];
}
Max2 = Sum-min; Array of all elements and minus the most small segments and
return max1 > Max2?     MAX1:MAX2;; Returns a larger value
}

The first part is to find the maximum value of the first case (MAX1 with the variable max), the second part of the first TMP is the most small section and, then the TMP value is sum-tmp, and finally Max takes both large numbers.
Method Two:
Method Two transforms the problem into another problem: since the end and end of a number can be connected, we can copy the array and receive our own back, and then we'll try to make a novelty of the largest array of arrays, but here we have to limit the condition that the maximum size of the sub array can not exceed N. So we turn the problem into an extension question 3, which I will introduce in the third part.
Method Three:
Method Three is introduced in the book "The Beauty of programming", detailed see 188 pages, but I think this algorithm is wrong, may be I understand the author of the idea of a problem, I will be copied in the following solution, and a counter example, interested in the discussion of the students want to give me a message.
From the beauty of programming P188:
If the array (a[0],a[1],a[2],......, a[n-1]) is adjacent, that is, we allow a number (a[i],a[i+1) to be found,...... A[N-1],A[0],A[1],...., a[j]), make it and Max, how to do?
(1) The solution does not span a[n-1] to a[0] (original problem).
(2) The solution crosses a[n-1] to a[0].
For the 2nd case, just find the starting and largest segment (A[0],..., a[j]) (0<=j<n) and the largest section (A[n-1],..., a[i]) (a[n-1) at the end of the a[0, then in the 2nd case , and the maximum value of m_2 is:
M_2=A[I]+...+A[N-1]+A[0]+...+A[J]
If I <= J, then
M_2=A[0]+...+A[N-1]
Otherwise
M_2=A[0]+...+A[J]+A[I]+...+A[N-1]
Finally, it is possible to take the maximum value of two kinds of cases, to solve the problem of crossing a[n-1] to a[0] only need to traverse the array once, so the total time complexity is O (n) +o (n) =o (n).
Analytical:
There are no problems in the discussion of two kinds of situations, but the solution to the 2nd case I think is wrong, counter example:
Find the maximum 6,-1,-6,8,2 of an array of 5 elements and: The M_1 is 10, but if the above method is used, the m_2 result is 9, since the beginning and the largest section of a[0] is a[0],..., a[n-1] is 9, with a[n-1] ending and the largest section (a[i ],..., a[n-1]) as a[n-1], because these two paragraphs have intersection, so m_2= a[0]+...+a[n-1].
The final result is 9, two kinds of larger, then the result is 10. But the correct result is obviously 16.
The reason for this result: from the beginning of the a[0] and the biggest one is not wrong, but we hope that the result is not this paragraph, we hope to obtain a[0] this paragraph, so that there will not be two paragraphs intersect.
In the second part, I analyzed two expansion questions, and the next two extensions I will analyze in part three.
If I have written a wrong place above or you have a better way, I hope you can come forward and learn from each other.
Extension Question 2:
There is an integer sequence, which has a negative number, a positive number, where successive numbers sum, the sum of the absolute value of the largest string.
Analysis
Ideas
Maximum sub Matrix and
Copy Code code as follows:

#include <iostream>
#include <cstdio>
using namespace Std;
#include <memory.h>
int a[102][102];
int Maxsubarray (int *arr, int len)//Max Subsequence and
{
int i,sum=arr[0],b=0;
for (I=0;i<len;++i)
{
if (b>0)
B+=arr[i];
Else
B=arr[i];
if (b>sum)
Sum=b;
}
return sum;
}
int Maxsubmatrix (int n, int m,int array[102][102])
{
int i,j,h,max,sum=-100000;
int b[102];
for (i=0;i<n;i++)
{
Memset (b,0,sizeof (b)); Initialize b[]
for (j=i;j<n;j++)///Add the line I to line J and find the maximum for each addition
{
for (h=0;h<m;h++)
{
B[H]+=ARRAY[J][H]; The two-dimensional array is compressed into a one-dimensional array, and then the maximal subsequence and
}
Max=maxsubarray (B,H);
if (max>sum)
Sum=max;
}
}
return sum;
}
int main (void)
{
int n,i,j;
while (scanf ("%d", &n)!=eof)
{

for (i=0;i<n;i++)
{
for (j=0;j<n;j++)
scanf ("%d", &a[i][j]);
}
printf ("%d\n", Maxsubmatrix (N,n,a));
}
return 0;
}

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.