Home Backend Development PHP Tutorial Maximum subsequence and algorithm analysis

Maximum subsequence and algorithm analysis

Aug 10, 2016 am 08:48 AM
gt int lt return

Problem description: Given n integer sequences {a1, a2,...,an}, find the function f(i,j)=max{0,Σak}(k: continuously from i to j );

The problem is to find the maximum value of the sum of consecutive sub-series. If the maximum value is a negative number, take 0, such as the 8 number sequence {-1,2,-3,4,-2,5, -8,3}, the maximum subsequence sum of Namo is 4+(-2)+5=7.

This problem has four algorithms with different complexity. The time complexity of algorithms 1 to 4 is O(n 3),O(n2),O(nlogn),O(n);

Algorithm 1:

The most direct method is the exhaustive method. List all situations, and we can set the subsequence The left end i and the right end j, and then use a layer to calculate the sum from a[i] to a[j].

//Maximum sub-column and exhaustive method
#include
using namespace std;
int Find_Maxsun (int*a, int n);
int main(){
int n, i;
int a[100];
cin >> n;
cout << "Pleace Input The " << ; n << "Number:" << endl;
for (i = 0; i < n; i++)
cin >> a[i];
cout< return 0;
}
int Find_Maxsun(int*a, int n){
int MaxSun = 0, i, j, k;
int NowSum;
for (i = 0; i < n; i++) /*Left end of subsequence*/
for (j = 0; j < n; j++){ /*Right end of subsequence*/
NowSum = 0;
for (k = i; k < = j; k++)
NowSum += a[k]; /*Subsequence from a[i] to a[j]*/
if (NowSum>MaxSun)
MaxSun = NowSum; /*Update result*/
}
return MaxSun;
}

Obviously, the brute force method uses three for loops, and the algorithm time complexity is O(n3). This is of course the stupidest algorithm, but when the data is very large, Even if it is a rhythm that has to be calculated to death, we can clearly see the third level of for loop. Every time

j is added, the sum of the subcolumns has to be calculated again. So why don't we use the result of j-1? That is to say, we save the result of j-1. When calculating the result of step j, we only need to add a[j] on the basis of step j-1, so there is Algorithm 2.

Algorithm 2:

#include
using namespace std;
int Find_Maxsun2(int*a, int n);
int main(){
int n, i;
int a[100];
cin >> n;
cout << "Pleace Input The " << n << " Number:" << endl;
for (i = 0; i < n; i++)
cin >> a[i];
cout << Find_Maxsun2(a, n) << endl;
return 0;
}
int Find_Maxsun2(int*a, int n){
int i , j, NewSum = 0, MaxSum= 0;
for (i = 0; i < n; i++){ /*is the left endpoint of the sequence*/
NewSum = 0;
for (j = i; j < n; j++){ /*j is the right endpoint of the series*/
NewSum += a[j]; /*Update NewSum each time under j-1 condition*/
if (NewSum>MaxSum) /*Update MaxSum*/
MaxSum = NewSum;
}
}
return MaxSum;
}

This algorithm is smarter than 1, and the algorithm complexity is O(n2), which is obviously not the complexity we want.

Algorithm 3:

Algorithm 3 uses the idea of ​​​​divide and conquer. The basic idea is self-evident: first divide and then conquer, decompose the problem into small problems and then sum up the small problems to solve them. We divide the original sequence into one is two, then the largest subsequence is on the left, on the right, or across the boundary. The basic idea is as follows:

Step 1: Divide the original sequence into two, into a left sequence and a right sequence.

Step 2: Recursively find the subsequences S left and S right.

Part 3: Scan from the center line to both sides to find the largest subsequence across the center line and S.

Step 4: Find S=max{S left, S middle, S right};

The code is implemented as follows:

#include
using namespace std;
int Find_MaxSum3(int*a,int low,int high);
int Max(int ​​a,int b,int c);
int main(){
int n, i;
int a[100];
cin >> n;
cout << "Pleace Input The " << n << " Number:" << endl;
for ( i = 0; i < n; i++)
cin >> a[i];
cout << Find_MaxSum3(a,0,n-1) << endl;
return 0;
}
int Find_MaxSum3(int*a,int low,int high){
int MaxSum = 0, MidSum, LeftSum, RightSum,i;
MidSum = 0;
if (low == high){ /*Termination condition of recursion* /
if (a[low] > 0)
return a[low];
else
return 0;
}
int mid = (low + high) / 2; //Find the midpoint of the minute
LeftSum = Find_MaxSum3 (a, low, mid); /*Recursively find the maximum sum of the left sequence*/
RightSum = Find_MaxSum3(a, mid + 1, high); /*Recursively find the maximum subsequence sum of the right sequence*/
/*Then you can find Maximum sum of middle crossing border sequences*/
int NewLeft = 0,Max_BorderLeft=0, NewRight = 0,Max_BorderRight=0;
for (i = mid; i >= low; i--){ /*Scan left Find the maximum sum*/
NewLeft += a[i];
if (NewLeft > Max_BorderLeft)
Max_BorderLeft = NewLeft;
}
for (i = mid + 1; i <= high; i++){ /* towards Right scan to find the maximum subsequence sum */
NewRight+=a[i];
if (NewRight >= Max_BorderRight)
Max_BorderRight = NewRight;
}
MidSum = Max_BorderRight + Max_BorderLeft;
return Max(LeftSum, MidSum, RightSum) ; /*Return the result of the rule*/
}
int Max(int ​​a, int b, int c){ /*Find the largest number among the three*/
if ( a>= b&&a >= c)
return a;
if (b >= a&&b >= c)
return b;
if (c >= b&&c>=a)
return c;
}

Let’s calculate the time complexity of this algorithm :

T(1)=1;

T(n)=2T(n/2)+O(n);

=2kT(n/2k)+kO(n) =2kT(1)+kO(n) (where n=2k)=n+nlogn=O(nlogn);

Although this algorithm is very good, it is not the fastest algorithm .

Algorithm 4:

Algorithm 4 is called online processing. This means that every time a piece of data is read in, it is processed in time, and the result obtained is true for the currently read data, that is, the algorithm can give the correct solution at any position, and the algorithm can give the correct solution while reading.

#include
using namespace std;
int Find_MaxSum4(int*a, int n);
int main(){
int n, i;
int a[100];
cin >> n ;
cout << "Pleace Input The " << n << " Number:" << endl;
for (i = 0; i < n; i++)
cin >> ; a[i];
cout << Find_MaxSum4(a,n) << endl;
return 0;
}
int Find_MaxSum4(int*a, int n){
int i, NewSum = 0, MaxSum = 0;
for (i = 0; i < n; i++){
NewSum += a[i]; /*Current subsequence sum*/
if (MaxSum < NewSum)
MaxSum = NewSum; / *Update the maximum subsequence sum*/
if (NewSum < 0) /*Abandon it if it is less than 0*/
NewSum = 0;
}
return MaxSum;
}

This algorithm is to read the data one by one After scanning once, there is only one for loop. The algorithms for solving the same problem are very different. The trick lies in letting the computer remember some key intermediate results to avoid repeated calculations.

The above introduces the maximum subsequence and algorithm analysis, including aspects of the content. I hope it will be helpful to friends who are interested in PHP tutorials.

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

What are the differences between Huawei GT3 Pro and GT4? What are the differences between Huawei GT3 Pro and GT4? Dec 29, 2023 pm 02:27 PM

Many users will choose the Huawei brand when choosing smart watches. Among them, Huawei GT3pro and GT4 are very popular choices. Many users are curious about the difference between Huawei GT3pro and GT4. Let’s introduce the two to you. . What are the differences between Huawei GT3pro and GT4? 1. Appearance GT4: 46mm and 41mm, the material is glass mirror + stainless steel body + high-resolution fiber back shell. GT3pro: 46.6mm and 42.9mm, the material is sapphire glass + titanium body/ceramic body + ceramic back shell 2. Healthy GT4: Using the latest Huawei Truseen5.5+ algorithm, the results will be more accurate. GT3pro: Added ECG electrocardiogram and blood vessel and safety

Detailed explanation of the usage of return in C language Detailed explanation of the usage of return in C language Oct 07, 2023 am 10:58 AM

The usage of return in C language is: 1. For functions whose return value type is void, you can use the return statement to end the execution of the function early; 2. For functions whose return value type is not void, the function of the return statement is to end the execution of the function. The result is returned to the caller; 3. End the execution of the function early. Inside the function, we can use the return statement to end the execution of the function early, even if the function does not return a value.

Detailed explanation of the method of converting int type to bytes in PHP Detailed explanation of the method of converting int type to bytes in PHP Mar 06, 2024 pm 06:18 PM

Detailed explanation of the method of converting int type to byte in PHP In PHP, we often need to convert the integer type (int) to the byte (Byte) type, such as when dealing with network data transmission, file processing, or encryption algorithms. This article will introduce in detail how to convert the int type to the byte type and provide specific code examples. 1. The relationship between int type and byte In the computer field, the basic data type int represents an integer, while byte (Byte) is a computer storage unit, usually 8-bit binary data

What is the execution order of return and finally statements in Java? What is the execution order of return and finally statements in Java? Apr 25, 2023 pm 07:55 PM

Source code: publicclassReturnFinallyDemo{publicstaticvoidmain(String[]args){System.out.println(case1());}publicstaticintcase1(){intx;try{x=1;returnx;}finally{x=3;}}}#Output The output of the above code can simply conclude: return is executed before finally. Let's take a look at what happens at the bytecode level. The following intercepts part of the bytecode of the case1 method, and compares the source code to annotate the meaning of each instruction in

Fix: Snipping tool not working in Windows 11 Fix: Snipping tool not working in Windows 11 Aug 24, 2023 am 09:48 AM

Why Snipping Tool Not Working on Windows 11 Understanding the root cause of the problem can help find the right solution. Here are the top reasons why the Snipping Tool might not be working properly: Focus Assistant is On: This prevents the Snipping Tool from opening. Corrupted application: If the snipping tool crashes on launch, it might be corrupted. Outdated graphics drivers: Incompatible drivers may interfere with the snipping tool. Interference from other applications: Other running applications may conflict with the Snipping Tool. Certificate has expired: An error during the upgrade process may cause this issu simple solution. These are suitable for most users and do not require any special technical knowledge. 1. Update Windows and Microsoft Store apps

C++ program to convert double type variable to int type C++ program to convert double type variable to int type Aug 25, 2023 pm 08:25 PM

In C++, variables of type int can only hold positive or negative integer values; they cannot hold decimal values. There are float and double values ​​available for this purpose. The double data type was created to store decimals up to seven digits after the decimal point. Conversion of an integer to a double data type can be done automatically by the compiler (called an "implicit" conversion), or it can be explicitly requested by the programmer from the compiler (called an "explicit" conversion). In the following sections, we'll cover various conversion methods. Implicit conversions The compiler performs implicit type conversions automatically. To achieve this, two variables are required - one of floating point type and the other of integer type. When we simply assign a floating point value or variable to an integer variable, the compiler takes care of all the other things

What is the value range of int32? What is the value range of int32? Aug 11, 2023 pm 02:53 PM

The value range of int32 is from -2 to the 31st power to 2 to the 31st power minus 1, that is, -2147483648 to 2147483647. int32 is a signed integer type, which means it can represent positive numbers, negative numbers, and zero. It uses 1 bit to represent the sign bit, and the remaining 31 bits are used to represent the numerical value. Since one bit is used to represent the sign bit, the effective number of int32 bits is 31.

How to convert int to string type in go language How to convert int to string type in go language Jun 04, 2021 pm 03:56 PM

Conversion method: 1. Use the Itoa() function, the syntax "strconv.Itoa(num)"; 2. Use the FormatInt() function to convert int type data into the specified base and return it in the form of a string, the syntax "strconv .FormatInt(num,10)".

See all articles