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}