Problem description: There is a sequence like 23,-23,11, 43,-45, 29, 34,0, 23,-12 to find the sum of the largest subsequences in this sequence, for example, from 0th to 3rd elements are a sub-sequence with the sum of 54. The shortest sub-sequence can have only one element, and the longest sub-sequence can contain all elements.
The following is an algorithm for solving this problem (implemented in Java ):
Algorithm 1 is the first algorithm we think of. It is a very easy-to-understand algorithm, but it has the lowest efficiency. The average time complexity is O (n ^ 3 ):
Public static int getMaxSubVector1 (int [] m ){
Int maxSubVector = 0;
Int I, j = 0, k = 0;
For (I = 0; I <m. length; I ++ ){
For (j = I; j <m. length; j ++ ){
Int sum = 0;
For (k = I; k <j; k ++ ){
Sum + = m [k];
MaxSubVector = Math. max (maxSubVector, sum );
}
}
}
Return maxSubVector;
}
Algorithm 2, a slightly improved algorithm with an average time complexity of O (n ^ 2)
Public static int getMaxSubVector2 (int [] m ){
Int maxSubVector = 0;
Int I, j = 0;
For (I = 0; I <m. length; I ++ ){
Int sum = 0;
For (j = I; j <m. length; j ++ ){
Sum + = m [j];
MaxSubVector = Math. max (maxSubVector, sum );
}
}
Return maxSubVector;
}
Algorithm 3, we can solve this problem using the idea of the divide and conquer algorithm, so that we can reduce the average time complexity to O (nlogn ):
Public static int getMaxSubVector4 (int [] B, int l, int u ){
Int sum = 0;
Int m = (l + u)/2;
If (l> u) return 0;
If (l = u) return Math. max (0, B [1]);
Int lmax = sum = 0;
For (int I = m; I> = 1; I --){
Sum + = B [I];
Lmax = Math. max (lmax, sum );
}
Int rmax = sum = 0;
For (int I = u; I> m; I --){
Sum + = B [I];
Rmax = Math. max (rmax, sum );
}
Return max3 (lmax + rmax, getMaxSubVector4 (B, l, m), getMaxSubVector4 (B, m + 1, u ));
}
Public static int max3 (int x, int y, int z ){
If (x <y ){
X = y;
}
If (x> z ){
Return x;
}
Return z;
}
Algorithm 4: this algorithm is a scanning idea and a linear time O (n ):
Public static int getMaxSubVector5 (int [] B ){
Int maxSubVector = 0;
Int maxEnding = 0;
For (int I = 0; I <B. length; I ++ ){
MaxEnding = Math. max (maxEnding + B [I], 0 );
MaxSubVector = Math. max (maxSubVector, maxEnding );
}
Return maxSubVector;
}
NOTE: For the above algorithm ideas, refer to the second edition of programming Pearl River