天天看點

聯機算法——最大子數組問題

代碼

public class Max {
    private static int max ( int [] a ) {
        int sum = , thisSum = ;

        for ( int i = ; i < a.length-; i++ ) {
            thisSum += a[i];

            if ( thisSum > sum ) 
                sum = thisSum;
            else if ( thisSum <  )
                thisSum = ;
        }

        return sum;
    }

    //測試
    public static void main( String [] args) {
        int [] a = { , -, , -, -, , , -};
        System.out.println( max(a) );
    }
}
           

輸出

11
           

簡要分析

聯機算法正确性不易看出,也難開發。

但僅需常量空間并以線性時間運算。