最大连续子段和

 
#include<stdio.h>
#include <malloc.h>
#define MAX 100
int main()
{
	int n;
	while((scanf("%d",&n))!=EOF && n>0)
	{
		int *a,*dp;
		a=(int *)malloc(sizeof(int)*n);
		dp=(int *)malloc(sizeof(int)*n);
			int i;
		for(i=0;i<n;i++)
			scanf("%d",&a[i]);
		int max=dp[0]=a[0];
	
		for(i=1;i<n;i++)
		{
			if(dp[i-1]>0)
				dp[i]=dp[i-1]+a[i];
			else
				dp[i]=a[i];
			if(dp[i]>max)
				max=dp[i];
		}
		printf("%d\n",max);

	}
	return 0;
}

最大连续问题是经典的算法问题之一,目标是从给定的一维数组中找到一个连续数组,使其元素之达到最大值。 ### 解法一:动态规划 (时间复杂度 O(n) ) 我们通过动态规划的思想解决该问题。核心思路是记录当前的最大以及全局最大: ```cpp #include <iostream> #include <vector> #include <algorithm> using namespace std; int maxSubArraySum(const vector<int>& nums) { int n = nums.size(); if (n == 0) return 0; // 空数组直接返回 int currentMax = nums[0]; // 当前位置的最大 int globalMax = nums[0]; // 全局最大 for(int i = 1; i < n; ++i){ currentMax = max(nums[i], currentMax + nums[i]); // 如果前面累加的结果小于当前数字本身,则从当前位置重新开始计算 globalMax = max(globalMax, currentMax); // 更新全局最大值 } return globalMax; } int main(){ vector<int> arr = {-2, 1, -3, 4, -1, 2, 1, -5, 4}; cout << "最大连续: " << maxSubArraySum(arr) << endl; } ``` #### 关键点解释: - **currentMax** 表示以第 `i` 个数结尾的“最大”。如果之前的累积为负数,那么它对后续无贡献,可以选择丢弃。 - **globalMax** 记录了历史过程中遇到过的最大值。 --- ### 解法二:分治法 (Divide and Conquer) 将原数组分为两部分,并递归地求解左右两侧及跨中间的部分最大。 代码较为冗长,在此略去详细实现,但可以作为进一步学习的方向。 --- ###
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值