最大连续子序列和

#include 
#include 
#include 

using namespace std;

int maxConSeq(vector& arr)
{
	int length = arr.size();
	int max = 0; 
	int sum = 0;
	for (int i = 0; i < length; ++i)
	{
		sum = sum + arr[i];
		if (sum > max)
			max = sum;
		if (sum < 0)
			sum = 0;
	}
	return max;
}

int dynamic(vector& arr)
{
	int length = arr.size();
	vector dp(length + 1, 0);
	dp[0] = 0;
	for (int i = 1; i <= length; ++i)
	{
                //状态转移方程
		dp[i] = max(dp[i - 1] + arr[i - 1], arr[i - 1]);
	}

	int max = dp[0];

	for (int i = 1; i <= length; ++i)
	{
		if (max < dp[i])
			max = dp[i];
	}
	return max;
}

int main()
{
	vector arr = { 1, -3, 2, 8 , -9, 6 };
	cout << maxConSeq(arr) << endl;
	cout << dynamic(arr) << endl;
}

 

 

你可能感兴趣的:(最大连续子序列和)