The and of the maximal contiguous subsequence in an array.

Source: Internet
Author: User

10. To find the number of the largest continuous subsequence in an array

Reference Link: http://blog.csdn.net/butwang/article/details/4691974

Idea: If you already know in the former 0~k-1 total k elements, in the largest and for maxall[k-1], how to find 0~k k+1 elements of maxall[k]. If the maximum and subsequence of the first k elements includes a[k-1], it is easy to know maxall[k] = max (Maxall[k-1] + a[k], a[k]). What if the largest and subsequence of the first k elements does not include a[k-1]? Adding an element after the array will change the maxall[k of the last face sequence of the array, so the "= Max" (Maxall[k-1], maxall[k-1] + a[k], a[k]). Defines endmax[k-1] as the largest subsequence and of the first k elements including A[k-1]. The recursive formula is as follows:

Endmax[k] = max (Endmax[k-1] + a[k], a[k])

Maxall[k] = max (maxall[k-1], endmax[k])

As you can see, there is no need to use two arrays, you can use two variables instead of maxall[k] and endmax[k].

Code:

1  Packagealgorithm;2 3  Public classMaxsubsum {4     //the maximum number of sub-sequences in an array5      Public Static voidMain (string[] args) {6         intA[] = {-3, 3,-1, 4,-2,-1 };7 8         intAllMax = a[0];9         intEndmax = a[0];Ten  One         intAllmaxstart = 0, allmaxend = 0, Endmaxstart = 0, endmaxend = 0; A  -          for(inti = 1; i < a.length; i++) { -             if(Endmax + a[i] >A[i]) { theEndmax = Endmax +A[i]; -Endmaxend =i; -}Else { -Endmax =A[i]; +Endmaxstart =i; -Endmaxend =i; +             } A              at             if(Endmax >AllMax) { -AllMax =Endmax; -Allmaxstart =Endmaxstart; -Allmaxend =Endmaxend; -             } -         } in          -System.out.println ("MaxValue:" +allmax+ ", Start:" +allmaxstart+ ", End:" +allmaxend); to     } +}

The and of the maximal contiguous subsequence in an array.

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.