求数组中最大和子串类问题

public class maxsub {
	/*
	 * 基于的性质:	1.对于全负的元素,找到最大值即可
	 * 			2.对于最大子串和大于0的,可证明最大子串中任意前缀串大于0
	 * 
	 * 算法:依次计算累加和,当累加和大于原累加和时记录最大值相关信息,当累加和小于零时,由下一元素重新累加
	 */
	static int getmaxsub(int[] a) throws Exception{
		if(null==a||a.length<=0)
			throw new Exception();
			
		int maxhead=0,maxend=0,max=Integer.MIN_VALUE;
		int head=0,sum=0;
		for(int i=0;i<a.length;i++){
			sum+=a[i];
			if(sum>max){
				max=sum;
				maxhead=head;
				maxend=i;
			}
			if(sum<0){
				head=i+1;
				sum=0;
			}
		}
		System.out.printf("\nmaxsub is %d to %d sum=%d\n",maxhead,maxend,max);
		return max;
	}
	
	static int getMaxsub(int[] a) throws Exception{
		if(null==a||a.length<=0)
			throw new Exception();
			
		int sum=0,max=Integer.MIN_VALUE;
		for(int i=0;i<a.length;i++){
			sum+=a[i];
			if(sum>max)
				max=sum;
			if(sum<0)
				sum=0;
		}
		return max;
	}
	
	static int[] getMaxsub(int[] a,int start,int end) throws Exception{
		if(null==a||start>=end)
			throw new Exception();
			
		int maxhead=0,maxend=0,max=Integer.MIN_VALUE;
		int head=0,sum=0;
		for(int i=start;i<end;i++){
			sum+=a[i];
			if(sum>max){
				max=sum;
				maxhead=head;
				maxend=i;
			}
			if(sum<0){
				head=i+1;
				sum=0;
			}
		}
		return new int[] {max,maxhead,maxend};
	}
	
	public static void main(String[] argvs) throws Exception{
		int[] a={-2, 1, -3, 4, -1, 2, 1, -5, 4};
		getmaxsub(a);
		System.out.println(getMaxsub(a));
		int[] b = getMaxsub(a,0,a.length);
		System.out.println(Math.max(getMaxsub(a, 0, b[1])[0],getMaxsub(a,b[2],a.length)[0]));
	}
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值