implement the maximum subarray using dynamic programming

本文介绍了一种解决最大子段和问题的线性时间复杂度算法——Kadane算法,并通过一个具体的C++代码示例展示了算法的具体实现过程。该算法能够有效地找到一维数组中具有最大和的连续子数组。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

the time complexity is O(n).
/*  modified by quanspace 2013-01-30 
 *  实现最大子段和问题的线性级的算法 a linear time algorithm from Jay Kadane 
 *  最大子段和 maxsum 要么是空,取特定值0, 要么是 a[i]..a[j] 0<= i<= j<=n .
 *  a simple exeample of dynamic programming
 * */
# include <iostream>
using namespace std;
struct max_subarr{
		int ix_start;
        int ix_end;
		int maxsum;
};
int main(){
		int a[16] = {13, -3, 20, -25, -3, -16, -23, 18, 20, -7, 12, -5, -22, 15, -4, 7};
        max_subarr ans;
		ans.ix_start = 0, ans.ix_end = 0;
		ans.maxsum = a[0];
		int maxsum_temp = a[0];
		for(int i = 1; i<16; ++i){
				maxsum_temp += a[i];
				if(maxsum_temp<a[i]){
						maxsum_temp = a[i];
						ans.ix_start = i;
				}
				if(maxsum_temp>ans.maxsum){
						ans.maxsum = maxsum_temp;
						ans.ix_end = i;
				}
		}
		cout<<"The array is : ";
		for(i = 0; i<16; ++i)
				cout<<a[i]<<" ";
		cout<<endl;
		cout<<"The maxmum subarray is ";
		for(i = ans.ix_start; i<= ans.ix_end; ++i)
			 cout<<a[i]<<" ";
		cout<<endl;
		cout<<"the maxsum is : "<<ans.maxsum<<endl;
		return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值