【1】 最大子序列和问题
来源:互联网 发布:360数据恢复大师损坏 编辑:程序博客网 时间:2024/05/07 03:20
#include <iostream>
using std::cout;
using std::cin;
using std::endl;
#include <vector>
using std::vector;
// function declarations
int maxSubSum1(const vector<int> &a);
int maxSubSum2(const vector<int> &a);
int maxSubSum3(const vector<int> &a);
int maxSubSum4(const vector<int> &a);
int main()
{
vector<int> iv{ 4, -3, 5, -2, -1, 2, 6, -2 };
cout << "max sub sum1: " << maxSubSum1(iv) << endl;
cout << "max sub sum2: " << maxSubSum2(iv) << endl;
cout << "max sub sum3: " << maxSubSum3(iv) << endl;
cout << "max sub sum4: " << maxSubSum4(iv) << endl;
cout << endl;
system("pause");
return 0;
}
int maxSubSum1(const vector<int> &a)
{
int res = 0, sz = a.size();
int i, j, k;
for (i = 0; i < sz; ++i)
for (j = i; j < sz; ++j)
{
int thisSum = 0;
for (k = i; k <= j; ++k)
thisSum += a[k];
if (thisSum > res)
res = thisSum;
}
return res;
}
int maxSubSum2(const vector<int> &a)
{
int maxSum = 0, thisSum = 0;
int sz = a.size();
int i, j;
for (i = 0; i < sz; ++i)
{
for (j = i; j < sz; ++j)
{
thisSum += a[j];
if (thisSum > maxSum)
maxSum = thisSum;
}
thisSum = 0;
}
return maxSum;
}
int max3(int a, int b, int c)
{
int res = a;
if (b > res) res = b;
if (c > res) res = c;
return res;
}
int maxSumRec(const vector<int> &a, int left, int right)
{
if (left == right)
if (a[left] > 0)
return a[left];
else
return 0;
int center = (left + right) / 2;
int maxLS = maxSumRec(a, left, center);
int maxRS = maxSumRec(a, center + 1, right);
int maxLBS = 0, LBS = 0;
for (int i = center; i >= left; --i)
{
LBS += a[i];
if (LBS > maxLBS)
maxLBS = LBS;
}
int maxRBS = 0, RBS = 0;
for (int j = center+1; j <= right; ++j)
{
RBS += a[j];
if (RBS > maxRBS)
maxRBS = RBS;
}
return max3(maxLS, maxRS, maxLBS + maxRBS);
}
int maxSubSum3(const vector<int> &a)
{
return maxSumRec(a, 0, a.size() - 1);
}
int maxSubSum4(const vector<int> &a)
{
int maxSum = 0, thisSum = 0;
for (int i = 0; i < a.size(); ++i)
{
thisSum += a[i];
if (thisSum > maxSum)
maxSum = thisSum;
else if (thisSum < 0)
thisSum = 0;
}
return maxSum;
}
- 【1】 最大子序列和问题
- 最大和子序列问题
- 最大子序列和问题
- 最大子序列和问题
- 最大子序列和问题
- 最大子序列和问题
- 最大子序列和问题
- 最大子序列和问题
- 最大子序列和问题
- 最大子序列和问题
- 最大子序列和问题
- 最大子序列和问题
- 最大子序列和问题~~
- 最大子序列和问题
- 最大子序列和问题
- 最大子序列和问题
- 最大子序列和问题
- 最大子序列和问题
- 808A Lucky Year
- java实现简单的登录验证码
- Linux基础(3)
- hdu 1114 Piggy-Bank(必须装满的完全背包)
- 双向循环链表
- 【1】 最大子序列和问题
- 1145: 统计字母个数
- java加密与解密的艺术(七)——因电子邮件传输诞生的Base算法家族
- auto_ptr、shared_ptr、weak_ptr、scoped_ptr用法小结
- 微信支付红包Java
- DAG上的动态规划
- Spring 自定义对象初始化及销毁
- 数据库的一些基本操作
- 面试:----面试中遇到的问题