To find the maximum sub-sequence

Source: Internet
Author: User

C++:

#include <stdint.h>
#include <string>
#include <iostream>
#include <vector>
using namespace Std;

int maxsubsum (const vector<int> &a) {
int maxsum = 0;
int thissum = 0;
for (int i = 0; i < a.size (); i++) {
Thissum + = A[i];
if (thissum>maxsum)
Maxsum = Thissum;
else if (Thissum < 0)
thissum = 0;
}
return maxsum;
}

int main () {
Vector<int> A = {4,-1, 3,-7,-4, 5, 6,-9, 8};
Cout<<maxsubsum (a) <<endl;
System ("pause");

}

Dynamic programming, online algorithms (on-line algorithm)

Online algorithm: At any time, the algorithm to the operation of the data read only (scan) once, once read into and processing, it does not need to be remembered. In this process, the algorithm can immediately give the correct answer to the corresponding sub-sequence problem for the data it has been read into. Algorithms with this feature are called online algorithms (on-line algorithm).

Algorithm complexity O (n)

Method 2:

Using the idea of recursion, the sequence is divided into the left half, the right half and the middle part, in which the left and the parts can be solved by recursion .

The middle part is the maximum value of the first half (which contains the last element of the left half) and the maximum value of the right half, which contains the right half of the value, and

Comparing these three values is the final result.

Algorithmic complexity: O (N*LOGN)

To find the maximum sub-sequence

Related Article

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.