Returns the sum of the largest consecutive subsequences in an array.

Source: Internet
Author: User

Returns the sum of the largest consecutive subsequences in an array.
10. Calculate the sum of the maximum continuous subsequences in an array

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

Idea: If you already know the first 0 ~ K-1 in total k elements, in the maximum and MaxAll [k-1], how to calculate 0 ~ K is a total of k + 1 elements of MaxAll [k]. If the largest and subsequences of the first k elements include a [k-1], it is easy to know that MaxAll [k] = max (MaxAll [k-1] + a [k], a [k]). What if the largest and subsequences of the first k elements do not include a [k-1? Adding an element behind the array will change the sum of the last face sequence of the array, so MaxAll [k] = max (MaxAll [k-1], MaxAll [k-1] + a [k], a [k]). Define EndMax [k-1] as the maximum 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])

We can see that there is no need to use two arrays. You can use two variables to replace MaxAll [k] And EndMax [k].

Code:

1 package algorithm; 2 3 public class maxSubSum {4 // calculate the largest subsequence in an array and 5 public static void main (String [] args) {6 int a [] = {-3, 3,-1, 4,-2,-1}; 7 8 int AllMax = a [0]; 9 int EndMax = a [0]; 10 11 int AllMaxStart = 0, AllMaxEnd = 0, EndMaxStart = 0, EndMaxEnd = 0; 12 13 for (int I = 1; I <. length; I ++) {14 if (EndMax + a [I]> a [I]) {15 EndMax = EndMax + a [I]; 16 EndMaxEnd = I; 17} else {18 EndMax = a [I]; 19 EndMaxStart = I; 20 EndMaxEnd = I; 21} 22 23 if (EndMax> AllMax) {24 AllMax = EndMax; 25 AllMaxStart = EndMaxStart; 26 AllMaxEnd = EndMaxEnd; 27} 28} 29 30 System. out. println ("MaxValue:" + AllMax + ", Start:" + AllMaxStart + ", End:" + AllMaxEnd); 31} 32}

 

 

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.