最大子序列的3种不同时间复杂度的算法

第一种是最挫的O(N^2)的算法,就是直接暴力二重循环解之。

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


第二种的时间复杂度是O(NlogN),用到递归的方法,分治的思想,如果没有后面的的O(N)的算法,这个算法便体现了递归的威力。
public class MaxSubSum2 {
	public static int maxSumRec(int[] a,int left,int right){
		/*当这个数组只有一个元素的时候*/
		if(left == right)
			if(a[left] > 0)
				return a[left];
			else
				return 0;
		/*递归*/
		int center = (left + right) >> 1;
		int maxLeftSum = maxSumRec(a,left,center);
		int maxRightSum = maxSumRec(a, center+1, right);
		/*求左段的最大子序列*/
		int maxLeftBorderSum = 0,leftBorderSum = 0;
		for(int i = center;i >= left;i --){
			leftBorderSum += a[i];
			if(leftBorderSum > maxLeftBorderSum)
				maxLeftBorderSum = leftBorderSum;
		}
		/*求右段的最大子序列*/
		int maxRightBorderSum = 0,rightBorderSum = 0;
		for(int i = center + 1;i <= right;i ++){
			rightBorderSum += a[i];
			if(rightBorderSum > maxRightBorderSum)
				maxRightBorderSum = rightBorderSum;
		}
		/*返回左段,右段,中间段三者的最大值*/
		return max3(maxLeftSum,maxRightSum,maxLeftBorderSum + maxRightBorderSum);
	}
	/*max3方法*/
	private static int max3(int maxLeftSum, int maxRightSum, int i) {
		if(maxLeftSum >= maxRightSum && maxLeftSum >= i)
			return maxLeftSum;
		if(maxRightSum >= maxLeftSum && maxRightSum >= i)
			return maxRightSum;
		if(i >= maxRightSum && i >= maxLeftSum)
			return i;
		else 
			return i;
	}
	
	public static int maxSubSum2(int[] a){
		return maxSumRec(a, 0, a.length - 1);
	}
	
	public static void main(String[] args){
		int[] a =  {4,-3,5,-2,-1,2,6,-2};
		System.out.println(maxSubSum2(a));
	}
}

第三种是最聪明也是最简单的方法了,时间复杂度为O(N),代码简单易懂,用thisSum来记录每一次累加的结果,如果大于maxSum,就让maxSum = thisSum,如果thisSum小于0,便让thisSum重新清零,如此从头遍历到尾即可。
public class MaxSubSum3 {	
	public static int maxSubSum3(int[] a){
		int maxSum = 0,thisSum = 0;
		for(int i = 0;i < a.length;i ++){
			thisSum += a[i];
			
			if(thisSum > maxSum)
				maxSum = thisSum;
			if(thisSum < 0)
				thisSum = 0;
		}
		return maxSum;
	}
	
	public static void main(String[] args){
		int[] a = {4,-3,5,-2,-1,2,6,-2};
		System.out.println(maxSubSum3(a));
	}
}



你可能感兴趣的:(Java)