(java)整数数组中求最大连续子序列之和,并且记录开始和结束位置

题意:

如题目所示,就是求一个数组中最大连续子序列之和并且记录开始和结束下标。

这是经典的一个动态规划问题,时间复杂度为O(N)

public class TestMaxQueue {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		int[] num=new int[]{-2,11,-4,13,-5,-2};
		int[] num2=new int[]{-10 ,1 ,2 ,3 ,4 ,-5 ,-23 ,3 ,7, -21};
		int[] nums=new int[]{5 ,-8 ,3 ,2 ,5 ,0};
		int[] num4=new int[]{-2, 11, -4, 13, -5, 2, -5, -3, 12, -9};
		getmax(num4);
	}
	public static void getmax(int[] num){
		int s=0;
		int e=0;
		int max=0;
		int temp=0;
		int ts=0;
		for(int i=0;i<num.length;i++){
			temp=temp+num[i];
			if(temp<0){
				ts=i+1;
				e=i+1;
				temp=0;
			}else{
				if(temp>max){
					s=ts;
					e=i;
					max=temp;
				}
			}
		}
		System.out.println("maxsum="+max+",start:"+s+",end="+e);
	}

}
特别注意:当总和小于0的时候,应该是记录一个重新开始的坐标,到总和大于原来的max的时候才能记录新的起点坐标。

  • 0
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值