java算法----求最大子序列

package com.shuobaotang.interview;

/**
 * 求出最大子序列的值
 * 如果输入为:{-2,11,-4,13,-5,2}
 * 那么答案是20
 * @author yangjianzhou
 *
 */
public class Problem3 {

	public static void main(String[] args) {

		Problem3 p = new Problem3();
		int[] a = {-2,11,-4,13,-5,2};
		System.out.println(p.maxmunSubsequenceSum(a));
		
	}	
	
	public int maxmunSubsequenceSum(int [] a){
		
		int maxSum =0;
		int thisSum = 0;
		int seqEnd;
		int seqStart;
		for(int i=0,j=0;j<a.length;j++){
			thisSum =thisSum+a[j];
			if(thisSum>maxSum){
				maxSum = thisSum;
				seqStart =i;
				seqEnd =j;
			}else if(thisSum<0){
				i = j+1;
				thisSum =0;
			}
		}
		return maxSum;
	}
}



运行结果:
20

你可能感兴趣的:(java算法)