您的位置:首页 > 其它

数组中子序列最大和算法

2011-03-18 12:33 267 查看
昨天有同事去别的公司面试,考了这样一道题,说写得不好,问能不能有时间复杂度为数组长度的算法,这个应该不难,写了段代码,执行上应该没错。

int main(int argc, char* argv[]){ int a[]={10,3,-5,16,90,-100,90,6,-7}; int n =sizeof(a)/sizeof(int); int max = 0; int tmpmax = 0; for(int i=0;i<n;i++) { if(tmpmax+a[i]>max) { tmpmax = max = tmpmax+a[i]; } else { tmpmax = tmpmax+a[i]; if(tmpmax<0) tmpmax = 0; } } cout<<"MaxValue: "<<max<<endl; return 0; }嘿嘿,谁能看出那个数组中和最大的子序列是什么?? 应该是最简单的算法了,在网上搜了下,好些人写得有问题,误人子弟啊。

上面是没有考虑全负的情况,修正如下:

int a[]={-10,3,9,-16,-90,-100,-90,6,-7};
int n =sizeof(a)/sizeof(int);

int max = a[0];
int tmpmax = 0;

for(int i=0;i<n;i++)
{
if((tmpmax=tmpmax+a[i])>max)
{
max = tmpmax;
}
else
{
if(tmpmax<0)
{
if(max<0)
if(a[i]>max)
max = a[i];
else
tmpmax = 0;
}

}
}

cout<<"MaxValue: "<<max<<endl;
如果全负实际是做了一遍选择排序。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐