最大子序列和(java实现)

1、问题描述:略。

2、代码实现:

/**
 *最大子序列求和
 */
class MaxSubsequenceSumDemo {
	public int maxSubSum(int a[]) {
		int maxSum = 0;
		for(int i = 0; i<a.length; i++){
			for(int j = i; j<a.length; j++){
				int thisSum = 0;
				for(int k = i; k<=j; k++)
					thisSum += a[k];
				if(thisSum > maxSum) 
					maxSum = thisSum;
			}
		}
		return maxSum;
	}
	
	public int maxSubSum2(int a[]) {
		int maxSum = 0;
		for(int i = 0; i<a.length; i++){
			int thisSum = 0;
			for(int j = 0; j<a.length; j++){
				thisSum += a[j];
				if(thisSum > maxSum) 
					maxSum = thisSum;
			}
		}
		return maxSum;
	}
	
	public int maxSubSum3(int a[]) {
		int maxSum = 0,thisSum = 0;
		for(int j = 0; j<a.length; j++){
			thisSum += a[j];
			if(thisSum > maxSum)
				maxSum = thisSum;
			else if(thisSum < 0)
				thisSum = 0;
		}
		return maxSum;
	}
}

点赞

发表评论

电子邮件地址不会被公开。 必填项已用*标注