C + + solves maximum sub-sequences and problems

Source: Internet
Author: User

Maximum child columns and issues

Problem Description:

Given a sequence of K integers {N1, N2, ..., NK}, "Continuous child column" is defined as {Ni, ni+1, ..., Nj}, where 1 <= i <= J <= K. "Maximum child columns and" are defined as the and the largest of all contiguous child column elements. For example, given sequence {-2, 11,-4, 13,-5,-2}, its contiguous sub-columns {11,-4, 13} have the largest and 20. You are now asked to write a program that calculates the maximum sub-columns of a given integer sequence.

Input format:

Enter line 1th to give the positive integer k (<= 100000), and the 2nd line to give the k integers, separated by a space.

Output format:

Outputs the maximum child columns in a row. If all integers in the sequence are negative, the output is 0.

Input Sample:
6-2 11-4 13-5-2
Sample output:
20

Complete code: (Implemented as algorithm 4, below is detailed)

#include "stdafx.h"
#include "stdio.h"
#include "Stdlib.h"
#include <iostream>
using namespace Std;
int maxsubsequencesum (int a[],int n);
int _tmain (int argc, _tchar* argv[])
{
int n = 0;
int sum = 0;
scanf ("%d", &n);
int *a = new Int[n];
for (int i = 0;i<n;i++)
scanf ("%d", &a[i]);
sum = Maxsubsequencesum (a,n);
std::cout<<sum<<std::endl;
System ("pause");
return 0;

}

int maxsubsequencesum (int a[],int N)
{
int thissum,maxsum,i;
thissum = 0;
maxsum = 0;
int l = 0;
for (i = 0;i<n;i++)
{
Thissum + = A[i];
if (Thissum > Maxsum)
{
Maxsum = Thissum;
}
else if (Thissum < 0)
{
thissum = 0;
l++;
}
}
if (L = = N)
{
return 0;
}
Else
return maxsum;
}

algorithm One :

int maxsubsequencesum (int a[],int N)
{
int thissum,maxsum,i,j,k;
maxsum=0;

int l = 0;
for (i=0;i<10;i++)
for (j=i;j<10;j++)
{
thissum=0;
for (k=i;k<=j;k++)
THISSUM+=A[K];
if (thissum>maxsum)
Maxsum=thissum;
}

if (L = = N)
{
return 0;
}
Else
return maxsum;

}
Let's analyze This program, first of all it must be completely correct. Run time is O (n³), which depends entirely on lines 5th and sixth, and Line sixth has an O (1) statement contained in a triple nested for loop. The Loop size of line 2nd is n.

The second loop size is n-i, he may be small, but it may also be n. We have to assume the worst, and that may make the end of the world a little bigger. The third loop has a size of j-i+1, and we want to assume that it's size n. For this total, O (1*n*n*n) =o (n³). The total cost of statement 1 is only O (1), while statements 7 and 8 total overhead are only O (N²) because they are simply expressions inside the two-layer loop.

We will combine the cost of each statement to more accurately analyze the answer is θ (n³), and the above estimate of a factor of 6 (but this does not affect, because the constant does not affect the order of magnitude). The following is a detailed calculation process:

Accurate analysis is derived from this equation

The final answer is (n³+3*n²+2*n)/6

It is obvious that this algorithm is too time consuming to calculate excessively on lines 5th and 6th. Now there is an improved algorithm 2

We can avoid the cubic run time by removing a for loop.

Here is the function of this algorithm:

algorithm 2:

int maxsubsequencesum (int a[],int N)
{
int thissum,maxsum,i,j;
maxsum=0;

int l = 0;

for (i=0;i<10;i++)
{
thissum=0;
for (j=i;j<10;j++)
{


THISSUM+=A[J];
if (thissum>maxsum)
Maxsum=thissum;
}
}

if (L = = N)
{
return 0;
}
Else
return maxsum;


}

This algorithm is obviously O (N²) and there is a simpler algorithm whose relative time complexity is O (NLOGN) solution, now we describe it.

This algorithm can embody the advantages of recursive algorithm, and the method adopts a "divide and conquer" strategy. The idea is that the problem is divided into two roughly equal sub-problems, which are then solved recursively, which is a sub-section. The "cure" stage merges the solution of two sub-problems together and may do a little additional work, and finally get the solution of the whole problem.

In this problem, the maximum number of sub-sequences and may appear in 3 places. Or the whole appears in the left half of the input data, or it appears in the right half of the entire section. Or across the middle of the input data to occupy the left and right halves. The first two cases can be solved recursively. The maximum of the third case can be obtained by finding the largest of the first half and (including the last element of the first half) and the largest of the second half and (the first element containing the second half). Then add the two and add them together.

algorithm 3 :
static int maxsubsum (int a[],int left,int right)
{
 int maxleftsum,maxrightsum;
 int maxleftbordersum,maxrightbordersum;
 int leftbordersum,rightbordersum;
 int center,i;
 if (left==right)
 {
  if (a[left]>0)
   return a[Left];
        else
   return 0;
 }
 center = (left+right)/2;
  maxleftsum=maxsubsum (A,left,center);
  maxrightsum=maxsubsum (a,center+1,right);

maxleftbordersum=0; leftbordersum=0;
for (i=center;i>=left;i--)
{
Leftbordersum+=a[i];
if (leftbordersum>maxleftbordersum)

Maxleftbordersum=rightbordersum;

}
maxrightbordersum=0; rightbordersum=0;
for (i=center+1;i<=right;i++)
{
Rightbordersum+=a[i];
if (rightbordersum>maxrightbordersum)
Maxrightbordersum=rightbordersum;
}
Return Max3 (maxleftsum,maxrightsum,maxleftbordersum+maxrightbordersum);

}

int maxsubsequencesum (const int A[],int N)
{
Return Maxsubsum (a,0,n-1);
}

The general form of recursive procedure calls is to pass the input array along with the left and right boundaries, which define the part of the expedited group to be processed. The single-line driver starts the procedure by passing an array along with boundary 0 and N-1.

The first line to line fourth deals with baseline conditions. If left==right, then there is only one element, and when the element is nonnegative it is the maximum and subsequence. Left>right is not possible unless N is negative (but small disturbances in the program can cause this confusion). The two recursive invocations performed on line six and line seventh. As we can see, recursive invocation is always a problem that is less than the original problem, but the overall small disturbance of the program is likely to break this feature. Rows eighth to 12th and 13th to 17th are calculated to reach the two largest sum and number at the intermediate boundary. These two largest and and for expansion to the left and right sides of the largest and. The pseudo-routine Max3 returns the maximum of these three possible largest and largest.

Obviously, when programming, the algorithm 3 requires more effort than the previous two algorithms. However, a short program does not imply a program number. As we have seen in the table that shows the algorithm run time earlier, the algorithm is significantly faster than the first two algorithms, except for the minimum input.

The last algorithm is the most effective algorithm,

Algorithm 4:

int maxsubsequencesum (int a[],int N)
{
int thissum,maxsum,j;

int l = 0;
thissum=maxsum=0;

for (j=0;j<n;j++)
{
THISSUM+=A[J];
if (thissum>maxsum)
Maxsum=thissum;
else if (thissum<0)
thissum=0;
}

if (L = = N)
{
return 0;
}
Else
return maxsum;


}

The time complexity of algorithm 4 is O (N), which is linear. A bit of the algorithm is that it only scans the data once, once A[i] is read into the processing, it no longer needs to be remembered. Therefore, if the array is on a disk or tape, it can be read sequentially, without having to store any part of the array in main memory. Moreover, at any given moment, the algorithm can give the correct answer to the sub-sequence problem for the data it has read. Algorithms with this feature are called online algorithms. Online algorithms that only require constant space and run in linear time are almost perfect algorithms.

C + + solves maximum sub-sequences and problems

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.