最大子数组java实现

int[] a ={13,-3,-25,20,-3,-16,-23,18,20,-7,12,-5,-22,15,-4,7};最大子数组为a[7]~a[10] 和为43

一下为java实现,分治法,递归实现;

public class MaxSubarray {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		
		int[] a = {13,-3,-25,20,-3,-16,-23,18,20,-7,12,-5,-22,15,-4,7};
		Result result = findMaxSubarray(a, 0, 15);
		System.out.println(result.getLow()+" "+result.getHigh()+" "+result.getSum());

	}
	
	static Result findMaxCrossingSubarray(int[] a, int low ,int mid, int high){
		Result result = new Result();
		int leftSum = -2147483648;
		int sum = 0;
		for(int i = mid; i>=low ; i--){
			sum += a[i];
			if(sum > leftSum){
				leftSum = sum;
				result.setLow(i);
			}
		}
		
		int rightSum = -2147483648;
		sum = 0;
		for(int i = mid+1; i<=high ; i++){
			sum += a[i];
			if(sum > rightSum){
				rightSum = sum;
				result.setHigh(i);
			}
		}
		
		result.setSum(leftSum+rightSum);
		return result;
	} 
	
	static Result findMaxSubarray(int[] a, int low ,int high){
		
		if(low == high){
			Result result = new Result();
			result.setLow(low);
			result.setHigh(high);
			result.setSum(a[low]);
			return result;
		}
		else{
			int mid = (high+low)/2;
			Result leftResult = findMaxSubarray(a, low, mid);
			Result rightResult = findMaxSubarray(a, mid+1, high);
			Result crossResult = findMaxCrossingSubarray(a, low, mid, high);
			if(leftResult.getSum() >= rightResult.getSum() && leftResult.getSum() >= crossResult.getSum()){
				return leftResult;
			}else if(rightResult.getSum() >= leftResult.getSum() && rightResult.getSum() >= crossResult.getSum()){
				return rightResult;
			}else{
				return crossResult;
			}
		}
	}
	
}
public class Result {

	private int low;
	private int high;
	private int sum;
	
	
	
	public int getLow() {
		return low;
	}
	public int getHigh() {
		return high;
	}
	public int getSum() {
		return sum;
	}
	public void setLow(int low) {
		this.low = low;
	}
	public void setHigh(int high) {
		this.high = high;
	}
	public void setSum(int sum) {
		this.sum = sum;
	}
	
}

更多实现方法,参看:

http://blog.csdn.net/v_JULY_v/article/details/6444021

http://www.cnblogs.com/waytofall/archive/2012/04/10/2439820.html


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值