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