面試題一:找出最大和的連續子串


今天在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);
    }
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM