Maximum sub-segments and problems

Source: Internet
Author: User

Maximum sub-segments and issues:

A sequence of n integers (possibly negative numbers) a[1],a[2],a[3],..., A[n], and the maximum value of the sub-segments of the sequence, such as A[i]+a[i+1]+...+a[j]. When the given integer is negative, the defined sub-segment and is 0, according to this definition, the optimal value is:

Max{0,a[i]+a[i+1]+...+a[j]},1<=i<=j<=n
For example, when (a1,a2,a3,a4,a4,a6) = ( -2,11,-4,13,-5,-2), the maximum child segment and is 20.

1. You can use a simple algorithm 3 for loop to calculate the answer, the time complexity is O (n^3).

2. The problem can be broken down by the use of a divide-and-conquer approach.

Divide a[1n] into A[1N/2] and a[n/2+1n], the maximum field of a[1n] and there are three cases:
(1) Maximum sub-segments of a[1n] and the largest sub-segments and the same as A[1N/2]
(2) Maximum sub-segments of a[1n] and the largest sub-segments and the same as a[n/2n]
(3) Maximum sub-segments of a[1n] and for Ai++aj,1<=i<=n/2,n/2+1<=j<=n

The time complexity is O (NLOGN).

3. Dynamic Programming Method:

B[j]=max{a[i]++a[j]},1<=i<=j, and 1<=j<=n, the maximum number of sub-segments to be asked and for Max B[j],1<=j<=n.
by b[j] The definition is easy to know, when b[j-1]>0 b[j]=b[j-1]+a[j], otherwise b[j]=a[j]. So B[J] 's dynamic programming recursion is:
B[j]=max (B[j-1]+a[j],a[j]), 1<=j<=n.

Time Complexity of O (n)

This gives the code

 Public Static intMaxsum (int[] a) {intn =a.length; intsum = 0, b = 0;  for(inti=0; i<n; i++) {            if(b > 0) {b+=A[i]; }            Else{b=A[i]; } Sum= B>sum?b:sum; }                returnsum;
}

Test data:

 Public Static void Main (string[] args) {        int[] A = {-2, one, -4, -5, 2};                 System.out.println (Maxsum (a));

Results:

  20

  

Maximum sub-segments 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.