动态规划:java实现最大字段和问题

题目:给定由n个整数组成的序列a1,a2,a3.....an,求该序列某一字段的最大和,并返回序列的开始和结束位置。


使用动态规划的思想,以下实现方式的时间复杂度为O(n^2)

public class MaxSum {

	public argsOfMaxSum theMaxSum(int arr[],int length){
		int sum=0,begin=0,end=0;
		for(int i=0;i<length;i++){
			int thissum=0;
			for(int j=i;j<length;j++){
				thissum+=arr[j];
				if(thissum>sum){
					sum=thissum;
					begin=i;
					end=j;
				}
			}
		}
		return new argsOfMaxSum(sum, begin, end);
	}
	public static void main(String[] args) {
		int[] a={-2,11,-4,13,-5,-2};
		argsOfMaxSum maxsum=new MaxSum().theMaxSum(a,a.length);
		System.out.println("最大字段和:"+maxsum.theMaxSum+"\n"+"从"+maxsum.numBegin+"到"+maxsum.nunEnd);
	}

	public class argsOfMaxSum{
		public argsOfMaxSum(int theMaxSum, int numBegin, int nunEnd) {
			super();
			this.theMaxSum = theMaxSum;
			this.numBegin = numBegin;
			this.nunEnd = nunEnd;
		}
		public int theMaxSum;
		public int numBegin;
		public int nunEnd;
	}
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值