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.