连续子序列最大和问题(Java语言)


/*
* 连续子序列最大和问题
*/
public class MaxSonSeqSum {
	public static void main(String[] args) {
		int[] a = {-2,11,-4,13,-5,2};
		int[] b = {1,-3,4,-2,-1,6};
		
		System.out.println("a数组连续子序列最大和为:"+maxSubSeqSum3(a));
		System.out.println("b数组连续子序列最大和为:"+maxSubSeqSum2(b));
		System.out.println("a数组连续子序列最大和为:"+maxSubSeqSum(a));
		System.out.println("b数组连续子序列最大和为:"+maxSubSeqSum(b));
		
	}
	
	//立方算法O(n^3)
	public static int maxSubSeqSum3(int[] a) {
		int maxSum = 0;
		int thisSum;
		int i,j,k;
		
		for(i=0; i<a.length;i++) {
			for(j=i;j<a.length;j++) {
				thisSum = 0;
				for(k=i;k<=j;k++) {
					thisSum += a[k];
				}
				if(thisSum > maxSum) {
					maxSum = thisSum;
				}
			}
		}
		return maxSum;
	}
	
	//平方算法O(n^2)
	public static int maxSubSeqSum2(int[] a) {
		int maxSum = 0;
		int thisSum;
		int i,j;
		
		for(i=0;i<a.length;i++) {
			thisSum = 0;
			for(j=i;j<a.length;j++) {
				thisSum += a[j];
				
				if(thisSum > maxSum) {
					maxSum = thisSum;
				}
			}
		}
		return maxSum;
	}
	
	//线性算法O(n)
	public static int maxSubSeqSum(int[] a) {
		int maxSum = 0;
		int thisSum = 0;
		int i;
		
		for(i = 0; i<a.length; i++) {
			thisSum += a[i];
			
			if(thisSum > maxSum) {
				maxSum = thisSum;
			}else if (thisSum < 0) {
				thisSum = 0;
			}
		}
		return maxSum;
	}
}

点赞