今天在QQ群里,聽大牛們去面試,提到面試很多是校招的算法,但是當時沒想出來,其中一個題目是給定一組數,找出和最大的連續子串。
我想了想看自己能不能解決這個問題,這個問題難點不再如何找出,而在於能否在復雜度為O(n)的情形下解決這個問題。
沒想出來,就問百度老師了,在這記錄一下。
印象比較深的是http://blog.nlogn.cn/programming-pearls-the-maximum-sum-of-substring/
這篇文章非常形象的給出了算法,以及形象化的解釋,讓讀者較容易理解,在最后介紹復雜度為O(n)的巧妙解法,我看懂了如何求出最大的和,但是沒理解怎么找出對應的數組,后來根據算法原理,修改了一下,代碼如下:
package org.data.applications; /**look for the max sum of sub sequence * @author acer * */ public class MAxSumSubSeq { public static void main(String[] args) { int[] a = {-12, -11, -4, -13, -5, -32}; getMaxSumSeq(a); } private static void getMaxSumSeq(int[] a){ int rmax = Integer.MIN_VALUE; int sum = Integer.MIN_VALUE; int start = -1; int end = -1; int temp = -1; for(int i = 0 ;i<a.length;i++){ if(sum>0){ sum+=a[i]; }else{ sum = a[i]; temp = i; } if(sum>rmax){ start = temp; rmax= sum; end = i; } } for(int j = start;j<=end;j++){ System.out.print(a[j]+" "); } System.out.println("\nsum:"+rmax); } }