这个算法我在我的博客里使用动态规划做过,具体实现请参阅我的dp板块,下面给出书上最快的算法,时间复杂度为O(n),称之为线性算法。
#include <iostream>
using namespace std;
int x[10]={31,-41,59,26,-53,58,97,-93,-23,84};
int mmax(int a,int b)
{
return a>b?a:b;
}
int main()
{
int maxsofar=0,maxendinghere=0;
for(int i=0;i<10;i++)
{
maxendinghere=mmax(maxendinghere+x[i],0);
maxsofar=mmax(maxsofar,maxendinghere);
}
cout<<maxsofar<<endl;
return 0;
}
算法说明:假设我们解决了x[0...i-1]的问题,那么如何扩展为包含x[i]的问题呢?我们使用类似于分治算法的原理:前i个元素中,最大总和子数组要么在前i-1个元素中(我们
将其保存在maxsofar中),要么其结束位置为i(我们将其存贮在maxendinghere中)。
该代码十分简短,也很快。
下面给出一个平方算法:思路很容易理解的:
#include <iostream>
using namespace std;
int x[10]={31,-41,59,26,-53,58,97,-93,-23,84};
int mmax(int a,int b)
{
return a>b?a:b;
}
int main()
{
int maxsofar=0;
for(int i=0;i<10;i++)
{
int sum=0;
for(int j=i;j<10;j++)
{
sum+=x[j];
maxsofar=mmax(maxsofar,sum);
}
}
cout<<maxsofar<<endl;
return 0;
}