[數據結構與算法分析]最大子序列和問題 -學習筆記

Q:

給定整數A1,A2,A3.....An,求Aj-Ak相加的最大值

A:

public class MaxSub {
	public static void main(String[] args){
		int[] a = {-2,11,-4,13,-5,-2};
		System.out.println(method(a));
	}
	public static int method(int[] a){
		int maxSum = 0;
		int thisSum = 0;
		for(int i =0;i<a.length;i++){
			thisSum += a[i];
			if(thisSum>maxSum){
				maxSum = thisSum;
			}else if (thisSum<0) {
				thisSum = 0;
			}
		}
		return maxSum;
	}
}

這個算法是從數據結構與算法分析上抄來的,非常感嘆她的精巧。

這個算法的核心思想:只要前面相加的數列不是負數就不會影響往後相加的最大值。

簡直是算法精簡的模範了。。。活活精簡到O(n)

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章